Spring MVC提供的全局异常处理方式:
1、使用 Spring MVC 提供的简单异常处理器 SimpleMappingExceptionResolver
2、实现 Spring 的异常处理接口 HandlerExceptionResolver 自定义自己的异常处理器
3、使用 @ExceptionHandler 注解实现异常处理
简单异常处理器
springmvc 中自带了一个异常处理器叫 SimpleMappingExceptionResolver,该处理器实现了HandlerExceptionResolver 接口,全局异常处理器都需要实现该接口
使用 xml 文件配置 SimpleMappingExceptionResolver 对象:
<!-- springmvc提供的简单异常处理器 --><bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><!-- 定义默认的异常处理页面 --><property name="defaultErrorView" value="/WEB-INF/views/error.jsp"/><!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception --><property name="exceptionAttribute" value="ex"/><!-- 定义需要特殊处理的异常,这是重要点 --><property name="exceptionMappings"><props><!-- 指定最定义异常所在的包 --><prop key="com.example.exception.CustomException">/WEB-INF/views/custom_error.jsp</prop></props><!-- 还可以定义其他的自定义异常 --></property></bean>
在异常页面获取异常信息:${ex}
定义一个简单的异常类:
//定义一个简单的异常类public class ParamException extends RuntimeException {private String message = "参数异常!";public ParamException(){super("参数异常!");}public ParamException(String message) {super(message);this.message = message;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}}
使用 Java 配置类配置:
@Beanpublic HandlerExceptionResolver simpleMappingExceptionResolver() {SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();// 设置默认异常处理映射exceptionResolver.setDefaultErrorView("/WEB-INF/views/error.jsp");// 设置自定义异常处理映射:通过属性配置Properties properties = new Properties();properties.setProperty("com.example.exception.BusinessException", "/WEB-INF/views/biz.jsp")exceptionResolver.setExceptionMappings(properties);return exceptionResolver;}
实现 HandlerExceptionResolver 接口
@Componentpublic class MyExceptionHandler implements HandlerExceptionResolver {@Overridepublic ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {System.out.println("异常标记");ModelAndView modelAndView = new ModelAndView();if (ex instanceof ArithmeticException){modelAndView.setViewName("error");modelAndView.addObject("msg", ex.getMessage());} else {modelAndView.setViewName("index");modelAndView.addObject("msg", ex.getMessage());}return modelAndView;}}
使用 @ExceptionHandler 注解
- @ExceptionHandler 注解:统一处理某一类异常
- @ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理分开
- @ResponseStatus:将某种异常映射为HTTP状态码
使用 @ControllerAdvice 和 @ExceptionHandler 注解结合使用
官方文档:https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#webmvc-fn
