项目的说明html
MyExceptionHandler.javajava
@ControllerAdvice public class MyExceptionHandler { public static final String ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception { e.printStackTrace(); ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", request.getRequestURL()); mav.setViewName(ERROR_VIEW); return mav; } }
MyAjaxExceptionHandler.javagit
@RestControllerAdvice public class MyAjaxExceptionHandler { @ExceptionHandler(value = Exception.class) public JsonResult defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception { e.printStackTrace(); return JsonResult.errorException(e.getMessage()); } }
注意在验证这一步时,把MyExceptionHandler.java这个类给注释了,由于若是不注释的话,两个类都会拦截Exception了。ajax
下面在MyExceptionHandler.java的基础上配置spring
MyExceptionHandler.javashell
@RestControllerAdvice public class MyExceptionHandler { public static final String ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception { e.printStackTrace(); if (isAjax(request)) { return JsonResult.errorException(e.getMessage()); } else { ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", request.getRequestURL()); mav.setViewName(ERROR_VIEW); return mav; } } // 判断是不是ajax请求 public static boolean isAjax(HttpServletRequest httpRequest) { String xRequestedWith = httpRequest.getHeader("X-Requested-With"); return (xRequestedWith != null && "XMLHttpRequest".equals(xRequestedWith)); } }
参照上两步的验证,验证前先把MyAjaxExceptionHandler.java给注了。json
# 注意区分 # 在类上的注解 @ControllerAdvice @RestControllerAdvice # 在方法上的注解 @ExceptionHandler(value = Exception.class) # 在统一返回异常的形式配置中 类上的注解为@RestControllerAdvice 方法中返回ModelAndView对象就是返回页面,返回一个其余对象就会转换为json串,这样就实现了对页面请求和ajax请求中的错误的统一处理。