SpringMvc通过HandlerExceptionResolver处理程序的异常,包括处理器映射、数据绑定以及处理器执行时发生的异常。HandlerExceptionResolver仅有一个接口方法:ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)
,当发生异常时,SpringMvc将调用resolveException()方法,并转到ModelAndView 对应的视图中,作为一个异常报告页面反馈给用户。
HandlerExceptionResolver拥有4个实现类,分别是DefaultHandlerExceptionResolver、SimpleMappingExceptionResolver、AnnotationMethodHandlerExceptionResolver、ResponseStatusExceptionResolver
- 1.DefaultHandlerExceptionResolver
SpringMvc默认装配了DefaultHandlerExceptionResolver,它会将SpringMvc框架的异常转换为相应的响应状态码。
可以在web.xml中通过如下的配置为响应状态码配置一个对应的页面:
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
- 2.AnnotationMethodHandlerExceptionResolver
SpringMvc已默认注册了AnnotationMethodHandlerExceptionResolver,它允许通过@ExceptionHandler的注解指定处理特定的方法,如下所示:
@RequestMapping(value = "/throwException")
public String throwException(){
if(2>1){
throw new RuntimeException("hello error");
}
return "success";
}
@ExceptionHandler(RuntimeException.class)
public String handleException(RuntimeException e,HttpServletRequest request){
return "forward:/error.jsp";
}
当throwException()的处理方法调用时抛出一个RuntimeException异常,它回被处于同一处理器类中handleException()方法捕获。@ExceptionHandler可以指定多个异常,如@ExceptionHandler(AException.class、BException.class)。
3.ResponseStatusExceptionResolver
允许通过@ResponseStatus注解标注一个方法,用于处理特定类型的响应状态码。4.SimpleMappingExceptionResolver
若希望对所有异常进行统一处理,可以使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常。
异常映射配置:
<bean id="handlerExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 指定当控制器发生DataAccessException异常时,使用dataAccessFailure视图进行显示 -->
<prop key="org.springframework.dao.DataAccessException">dataAccessFailure</prop>
<!-- 指定当控制器发生TransactionException异常时,使用dataAccessFailure视图进行显示 -->
<prop key="org.springframework.transaction.TransactionException">dataAccessFailure</prop>
</props>
</property>
</bean>
也可以自己实现ExceptionResolver覆盖resolveException()接口方法的实现,编写自己的异常解析器,做一些特定的工作,如将异常信息保存到数据库中等。写好自定义的ExceptionResolver,在spingmvc.xml中注册一个Bean即可工作。