基于配置的异常处理器
HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver(默认异常处理)和SimpleMappingExceptionResolver(自定义异常处理)
在xml文件进行配置
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | <!--配置异常处理器--><bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
 <property name="exceptionMappings">
 <props>
 <!--
 properties的键表示处理器方法执行过程中出现的异常
 properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面
 -->
 <prop key="java.lang.ArithmeticException">error</prop>
 </props>
 </property>
 <!--
 exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享
 -->
 <property name="exceptionAttribute" value="ex"/>
 </bean>
 
 | 
controller进行配置
| 12
 3
 4
 5
 6
 
 | @RequestMapping("/test")public String test(){
 
 System.out.println(1/0);
 return "target";
 }
 
 | 
![image-20220501100452968]()
基于注解的异常处理器
//@ControllerAdvice将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {
| 12
 3
 4
 5
 6
 7
 
 | @ExceptionHandler(ArithmeticException.class)
 
 public String handleArithmeticException(Exception ex, Model model){
 model.addAttribute("ex", ex);
 return "error";
 }
 
 |