Spring 异常处理

今天在做项目的时候突然发现异常处理还有所欠缺,所有打算好好的加强一下异常的处理,顺便好好巩固以前学习的知识和增加新的知识。

首先看一看通过实现Spring的异常处理接口

  1. 实现Spring接口-HandlerExceptionResolver
public class ExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        // TODO Auto-generated method stub
        return null;
    }

}

这个接口只定义了一个返还值为ModelAndView的接口,看源码和注释就很容易知道它的用法了。
注释中说明:Implementors are typically registered as beans in the application context.是一个需要配置成一个Bean的形式。

<!-- 异常处理 -->
    <bean class="com.***.Exception.ExceptionResolver" />

以下便是一个小小的例子:

public class ExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {

        if (ex instanceof NullArgumentException) {
            HandlerMethod method=(HandlerMethod) handler;
            System.out.println(method.getMethod());
            System.out.println("异常拦截成功!");
            return new ModelAndView("redirect:/Test.jsp");
        }

        return null;
    }

}

写一个TestController模拟抛出异常

@RequestMapping("/Exception.do")
    public String ExceptionMethod() throws Exception {
        throw new NullArgumentException("模拟异常抛出");

    }

测试结果:
这里写图片描述
页面也跳转了:
这里写图片描述


同样也可以通过继承AbstractHandlerExceptionResolver类:

public class ExceptionResolver extends AbstractHandlerExceptionResolver{

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        // TODO Auto-generated method stub
        return null;
    }

}

注意:上面这种方式只能捕获抛出的异常,如果在Controller内被catch下的异常是不会被处理的!


2.通过使用@ControllerAdvice注解的方式实现异常的处理

@ControllerAdvice
public class WebExceptionHandler {

    @ExceptionHandler(NullPointerException.class)
    public ModelAndView nullPointException() {

        System.out.println("空指针异常!");
        return new ModelAndView("Test");
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值