gpt4 book ai didi

java - Spring MVC : the best way to handle exception for Ajax Request and normal request?

转载 作者:搜寻专家 更新时间:2023-10-31 20:33:48 25 4
gpt4 key购买 nike

我想在我的项目中定义一个通用的异常管理器,所以我使用@ControllerAdvice来做,代码片段如下:

@ExceptionHandler(Exception.class)
public ModelAndView handleAllException(HttpServletRequest request, Exception ex) throws Exception
{
LOGGER.error(ex.getMessage());

ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", request.getRequestURL());
mav.setViewName(ViewConstants.INTERNAL_ERROR_VIEW);
return mav;
}

它将返回一个常见的错误页面。这对于正常的请求异常非常有用。但是如果这是一个 Ajax 请求,结果就太丑了。所以我添加代码来判断它。添加的代码如下:

if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// return HTTP Status code and response message
} else {
// return error page name
}

我认为这不是最好的方法,有人有好的意见吗?

最佳答案

根据它们是否服务于 AJAX 请求,我将所有 Controller 放在不同的包中。然后我可以设置 #basePackages ControllerAdvice 注释上的元素相应地处理异常

更新:参见 RequestMapping#paramsRequestMapping#headers根据 header 和/或参数分离 Controller

关于java - Spring MVC : the best way to handle exception for Ajax Request and normal request?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29600167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com