SpringMVC全局异常————初识HandlerExceptionResolver

SpringMVC提供了统一的异常处理

这里只提供SpringMVC全局异常处理的简单应用,并不包含其原理,文中如有不妥,还请前辈们不吝赐教

SpringMVC提供了统一的异常处理,接口HandlerExceptionResolver,自定义类实现HandlerExceptionResolver接口,重写resolveException方法。使用此方法可以在Controller层不抛出异常的情况,自动捕获异常,进行处理,相关步骤如下:

CustomExceptionResolver

//全局异常处理器
public class CustomExceptionResolver implements HandlerExceptionResolver {

    //系统抛出的异常
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //handler就是处理器适配器要执行的Handler对象(只有method)
        //解析出异常类型。
        System.out.println("异常");
        CustomException customException = null;

        //如果该 异常类型是系统 自定义的异常,直接取出异常信息,在错误页面展示。
        if (e instanceof CustomException){
            customException = (CustomException) e;
        }else{

            //如果该 异常类型不是系统 自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)。
            customException = new CustomException("发生了一个未知的错误,请重试");
        }

        //错误信息
        String message = customException.getMessage();
        //将错误信息传到页面,并且指向错误页面
        return new ModelAndView("redirect:/Index.html","message",message);
    }
}

CustomException

//创建自定义异常
public class CustomException extends Exception {

    //异常信息
    private String message;

    public CustomException(String message) {
        super(message);
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

SpringMVC的配置文件中注入

<!--自定义异常-->
    <bean class="com.hqyj.IoT.exception.CustomExceptionResolver"/>

如果有兴趣,可以去看看,Spring中HandlerExceptionResolver部分的源码,想要了解其原理,还是看源码比较好。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值