異常處理思路
系統中異常包括兩類:預期異常和運行時異常runtimeexception,前者通過捕獲異常從而獲取異常信息,后者主要通過規范代碼開發、測試通過手段減少運行時異常的發生。
系統的dao、service、controller出現都通過throws Exception向上拋出,最后由springMVC前端控制器交由異常處理器進行異常處理,如下圖:

springMVC提供全局異常處理器進行統一的異常處理,一個系統只有一個異常處理器
1自定義異常類
對不同的異常類型定義異常類,繼承Exception
/** * Created by Alex on 2017/6/29. * 系統自定義異常類 */ public class CustomException extends Exception { //異常信息 public String message; public CustomException(String message){ super(message); this.message = message; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }
}
2配置全局異常處理器
思路:
系統遇到異常時,在程序中手動拋出,dao拋給service,service拋給controller,最后controller拋給前端控制器,前端控制器調用全局異常處理器。
全局異常處理器處理思路:
解析異常類型,若該異常類型是系統自定義的異常,直接取出異常信息在錯誤頁面展示即可。
如果不是系統自定義異常,構造一個系統自定義的異常類型,信息為“未知錯誤”
springMVC提供一個HandlerExceptionResolver
/** * Created by Alex on 2017/6/29. * 全局異常處理器 */ public class CustomExceptionResolver implements HandlerExceptionResolver{ /** * 系統拋出的異常 * @param httpServletRequest * @param httpServletResponse * @param o * @param e 系統拋出的異常 * @return */ @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { // 解析出異常類型 CustomException customException = null; // 若該異常類型是系統自定義的異常,直接取出異常信息在錯誤頁面展示即可。 if(e instanceof CustomException){ customException = (CustomException)e; }else{ // 如果不是系統自定義異常,構造一個系統自定義的異常類型,信息為“未知錯誤” customException = new CustomException("未知錯誤"); } //錯誤信息 String message = customException.getMessage(); ModelAndView modelAndView = new ModelAndView(); //將錯誤信息傳到頁面 modelAndView.addObject("message",message); //指向錯誤頁面 modelAndView.setViewName("error"); return modelAndView; } }
3配置錯誤頁面
<%-- Created by IntelliJ IDEA. User: Alex Date: 2017/6/29 Time: 20:06 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>失敗!</title> </head> <body> ${message} </body> </html>
4springMVC.xml中配置全局異常處理器
<!-- 全局異常處理器 只要類實現了HandlerExceptionResolver接口,就是一個全局異常處理器哦 --> <bean class="com.alex.ssm.exception.CustomExceptionResolver"/>
注意:
系統自定義異常,建議在項目所有的功能都完成后再進行添加。
