spring有默認的exception處理方式,但是很多時候我們都需要自定義異常處理:
下面是spring中exception的結構:
spring默認是採用SimpleMappingExceptionResolver來處理異常,我們自定義異常的處理方式只需要繼承DefaultHandlerException,複寫doResolveException方法,在這裏處理我們的異常處理方式:
1、自定義ExceptionHandler,將這個註冊成bean:屬於我們的自定義異常就返回錯誤信息,不屬於我們自定義的異常,就重定向到錯誤頁面
public class WbExceptionHandler extends DefaultHandlerExceptionResolver { private static final Logger logger = Logger.getLogger(WbExceptionHandler.class); @Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if (ex instanceof WbRuntimeException) { //判斷如果是屬於我們自定義的runtime異常,就是返回json格式的錯誤信息:設置response的響應錯誤碼,添加json格式的錯誤信息 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("error", ex.getMessage()); return modelAndView; } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); try { //重定向到error的controller中 response.sendRedirect(request.getContextPath() + "/error"); } catch (IOException e) { logger.error(e.getMessage()); } return new ModelAndView(); } } }
public class UserNotExitException extends WbRuntimeException { public UserNotExitException(){ super("用戶名或者密碼錯誤"); } }
2、自定義runtime異常信息
public class WbRuntimeException extends RuntimeException { public WbRuntimeException(String message) { super(message); } public WbRuntimeException() { } ; }
3、在拋出異常的時候就拋出我們自定義的異常就可以得到異常信息了:
throw new UserNotExitException();
對應json請求的時候,獲取錯誤信息:
error: function (data) {
console.log(data);
var message = eval('(' + data.responseText + ')');
alert(message.error);
}在web.xml中還可以配置錯誤代碼指定頁面:
<error-page> <error-code>404</error-code> <location>/WEB-INF/404_error.jsp</location> </error-page>