1. 異常處理思路
首先來看一下在springmvc中,異常處理的思路:
如上圖所示,系統的dao、service、controller出現異常都通過throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進行異常處理。springmvc提供全局異常處理器(一個系統只有一個異常處理器)進行統一異常處理。明白了springmvc中的異常處理機制,下面就開始分析springmvc中的異常處理。
2. 定義全局異常處理器
1、定義自定義異常類,繼承Exception
public class CustomException extends Exception { public String message; public Throwable throwable; public CustomException(String message){ super(message); this.message = message; } public CustomException(Throwable throwable){ super(throwable); this.throwable = throwable; } public Throwable getThrowable() { return throwable; } public void setThrowable(Throwable throwable) { this.throwable = throwable; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2、定義異常處理器
public class CustomExceptionResolver implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { // 解析出異常類型 CustomException customException = null; String message = ""; // 若該異常類型是系統自定義的異常,直接取出異常信息在錯誤頁面展示即可。 if(e instanceof CustomException){ customException = (CustomException)e; customException.getThrowable().getClass().getName(); }else{ // 如果不是系統自定義異常,構造一個系統自定義的異常類型,信息為“未知錯誤” customException = new CustomException("未知錯誤"); message = customException.getMessage(); } //錯誤信息 ModelAndView modelAndView = new ModelAndView(); //將錯誤信息傳到頁面 modelAndView.addObject("message",message); //指向錯誤頁面 modelAndView.setViewName("showError"); return modelAndView; } }
3、SpringMVC中配置全局異常處理器
<bean class="com.smart.exception.CustomExceptionResolver"/>
4、測試
@RequestMapping(value="") @ResponseBody public Map<String,Object> Register(User user) throws Exception{ Map<String,Object> map = new HashMap<String,Object>(); try{ boolean isSuccess = userService.Register(user); if(isSuccess){ map.put("tip", "success"); } else{ map.put("tip", "error"); } }catch (Exception e){ throw new CustomException("未知錯誤"); } return map; }