springMVC学习(9)-全局异常处理
一、异常处理思路:
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
二、自定义异常类 继承Exception
1 package com.cy.exception; 2 3 /** 4 * 系统 自定义异常类,针对预期的异常,需要在程序中抛出此类的异常 5 * @author chengyu 6 * 7 */ 8 public class CustomException extends Exception{ 9 10 public String message; 11 12 public CustomException(String message){ 13 super(message); 14 this.message = message; 15 } 16 17 public String getMessage() { 18 return message; 19 } 20 21 public void setMessage(String message) { 22 this.message = message; 23 } 24 }
三、全局异常处理器:
思路:
系统遇到异常,在程序中手动抛出,dao抛给service、service给controller、controller抛给前端控制器,前端控制器调用全局异常处理器。
全局异常处理器处理思路:
解析出异常类型
如果该 异常类型是系统 自定义的异常,直接取出异常信息,在错误页面展示
如果该 异常类型不是系统 自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)
1 package com.cy.exception; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 6 import org.springframework.web.servlet.HandlerExceptionResolver; 7 import org.springframework.web.servlet.ModelAndView; 8 9 /** 10 * 全局异常处理器 11 * @author chengyu 12 * 13 */ 14 public class CustomExceptionResolver implements HandlerExceptionResolver{ 15 16 /** 17 * ex 系统 抛出的异常 18 * handler就是处理器适配器要执行Handler对象(只有method) 19 */ 20 @Override 21 public ModelAndView resolveException(HttpServletRequest request, 22 HttpServletResponse response, Object handler, Exception ex) { 23 24 CustomException customException = null; 25 26 //解析出异常类型 27 //如果该 异常类型是系统 自定义的异常,直接取出异常信息,在错误页面展示 28 //如果该 异常类型不是系统 自定义的异常,构造一个自定义的异常类型(信息为“未知错误”) 29 if(ex instanceof CustomException){ 30 customException = (CustomException) ex; 31 }else{ 32 customException = new CustomException("未知错误!"); 33 } 34 35 ModelAndView modelAndView = new ModelAndView(); 36 modelAndView.addObject("message", customException.getMessage()); 37 modelAndView.setViewName("error"); 38 return modelAndView; 39 } 40 41 }