項目的說明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請求中的錯誤的統一處理。