Spring MVC 有以下 3 种处理异常的方式:
- 使用 Spring MVC 提供的简单异常处理器 SimpleMappingExceptionResolver。
- 实现 Spring 的异常处理接口 HandlerExceptionResolver,自定义自己的异常处理器。
- 使用 @ExceptionHandler 注解实现异常处理
@ExceptionHandler
@RequestMapping("/testExceptionHandle")
public String testExceptionHandle(@RequestParam("i") Integer i) {
System.out.println(10 / i);
return "success";
}
@ExceptionHandler({ ArithmeticException.class })
public String testArithmeticException(Exception e) {
System.out.println("打印错误信息 ===> ArithmeticException:" + e);
// 跳转到指定页面
return "error";
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>错误页面</title>
</head>
<body>
发生算术运算异常,请重新输出数据!
</body>
</html>
HandlerExceptionResolver
public interface HandlerExceptionResolver {
@Nullable
ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex);
}
springmvc-servlet.xml
<!--托管MyExceptionHandler-->
<bean class="net.biancheng.exception.MyExceptionHandler"/>
SimpleMappingExceptionResolver
springmvc-servlet.xml 中配置全局异常;
异常类名映射为视图名,即发生异常时使用对应的视图报告异常。
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 定义默认的异常处理页面,当该异常类型注册时使用 -->
<property name="defaultErrorView" value="error"></property>
<!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->
<property name="exceptionAttribute" value="ex"></property>
<!-- 定义需要特殊处理的异常,用类名或完全路径名作为key,异常页名作为值 -->
<property name="exceptionMappings">
<props>
<prop key="ArithmeticException">error</prop>
<!-- 在这里还可以继续扩展对不同异常类型的处理 -->
</props>
</property>
</bean>