【问题标题】:Spring MVC : the best way to handle exception for Ajax Request and normal request?Spring MVC:处理 Ajax 请求和正常请求异常的最佳方法?
【发布时间】:2015-06-18 11:01:00
【问题描述】:

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

@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
    }

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

【问题讨论】:

  • 这可能是要走的路。

标签: java ajax spring spring-mvc


【解决方案1】:

我建议在任何请求上设置错误响应代码,认为这是一种很好的做法,可以通知客户出现问题,而不取决于请求的类型。对于 ajax 请求,您可以返回相同的页面并通过错误代码识别问题。

【讨论】:

    【解决方案2】:

    如果你使用 jQuery 来发出请求,你可以使用如下:

    jQuery.ajaxSetup({
        headers: { 'ajax-request': true },
        statusCode: {
            400: function (xhr) {
                ...do something
            },
            500: function (xhr) {
                ...do something
            }
            ...
        }
    });
    

    【讨论】:

      【解决方案3】:

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

      更新: 请参阅 RequestMapping#paramsRequestMapping#headers 以根据标头和/或参数分隔控制器

      【讨论】:

        【解决方案4】:
        ...
        public class Application extends SpringBootServletInitializer {
        
        @Bean(name = "simpleMappingExceptionResolver")
        public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
            SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
            r.setDefaultErrorView("forward:/errorController");
            return r;
        }
        

        @Controller
        public class ErrorController {
        
            public static final Logger LOG = Logger.getLogger(ErrorController.class);
        
            @RequestMapping(value = "/errorController")
            public ModelAndView handleError(HttpServletRequest request,
                    @RequestAttribute("exception") Throwable th) {
        
                ModelAndView mv = null;
                if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                    if (isBusinessException(th)) {
                        mv = new ModelAndView("appAjaxBadRequest");
                        mv.setStatus(BAD_REQUEST);
                    } else {
                        LOG.error("Internal server error while processing AJAX call.", th);
                        mv = new ModelAndView("appAjaxInternalServerError");
                        mv.setStatus(INTERNAL_SERVER_ERROR);
                    }
                    mv.addObject("message", getUserFriendlyErrorMessage(th).replaceAll("\r?\n", "<br/>"));
                } else {
                    LOG.error("Cannot process http request.", th);
                    mv = new ModelAndView("appErrorPage");
                    mv.addObject("exeption", th);
                }
        
                return mv;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2015-04-28
          • 2021-08-31
          • 2015-09-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多