Spring MVC(7):异常处理

Spring MVC 异常处理


Spring MVC 通过 HandlerExceptionResolver 统一处理程序的异常,包括控制器映射、数据绑定和处理器执行过程中产生的异常;

HandlerExceptionResolver 有 4个实现类:DefaultHandlerExceptionResolver 、SimpleMappingExceptionResolver、AnnotationMethodExceptionResolver、ReponseStatusExceptionResolver;

DefaultHandlerExceptionResolver 

Spring MVC 默认装配 DefaultHandlerExceptionResolver ,它会将 Spring MVC 框架的异常转换为响应的状态码, 详见的异常和响应状态码转换列表见:https://docs.spring.io/spring/docs/4.3.13.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-rest-spring-mvc-exceptions
可以在 web.xml 中为这些状态码配置对应的页面,如下:
 
<error-page>
    <error-code>404</error-code>
    <location>/error_pages/404.htm</location>
</error-page>

AnnotationMethodExceptionResolver

Spring MVC 默认注册了 AnnotationMethodExceptionResolver,它允许通过 @ExceptionHandler 注解指定处理器处理特定异常的方法,如下:
 
@Controller
public class UserController {
    @ResuqestMapping("throwException")
    public String throwException(){
        if(Math.random()*2 > 1)
            throw new RuntimeException("this is a exception");
        retrun "success";
    }
    @ExceptionHandler(RuntimeException.class)
    public String handleException(RuntimeException re,HttpServletRequest request){
        return "forward:error.jsp";
    }
}

SimpleMappingExceptionResolver

SimpleMappingExceptionResolver 可以用于对所有异常进行统一处理,将异常类名映射为视图名,即发生异常时使用对应的视图报告异常;
如以下异常映射配置片段:
 
<bean id="handlerExceptionResolver" 
    class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMapping">
        <props>
            <prop key="org.springframework.dao.DataAccessException">dataAccessFailure</prop>
            <prop key="org.springframework.transaction.TransactionException">transactionFailure</prop>
        </props>
    </property>
</bean>
以上配置中,当控制器发生DataAccessException异常时,使用 dataAccessFailure 视图显示,当控制器发生 TransactionException 异常时,使用 transactionFailure 视图显示;

自定义异常处理器

如果实现自定义的异常处理器,只要继承该 ExceptionResolver 接口并实现接口方法 resolveException ,之后在spring-mvc 配置文件中 注册该 bean 即可;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值