SpringMVC异常处理三种方式

SpringMVC对异常的处理有三大类

  1. 自定义HandlerExceptionResolver
  2. 在controller类用@ExceptionHandler 写一个异常处理方法
  3. 写一个异常处理类用@ControllerAdvice作为全局异常处理类
1. 自定义HandlerExceptionResolver

1.自定义一个handlerExceptionResolver,记得在配置文件中把这个bean注册到IOC容器中,id名为handlerExceptionResolver。

public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println(ex.getMessage());
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("error400");
        modelAndView.addObject("ex",ex);
        return modelAndView;
    }
}

<bean class="com.yolyn.intercepters.MyExceptionResolver" id="handlerExceptionResolver"/>

如果配置了自定义的handlerExceptionResolver,那么默认的就会失效。

2. 使用SpringMVC自带的异常处理器处理异常
org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver,  //对应@ExceptionHandler    
org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,  //对应@ResponseStatus   
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver// 判断是否SpringMVC自带的异常  
2.1 @ExceptionHandler的用法

在Controller类中写一个专门处理异常的方法,添上@ExceptionHandler注解,可以指定处理的异常类
如果有多个异常处理方法都能处理这个异常,那么精确优先

@Controller
public class OutputController {
    private String msg;

    @RequestMapping("handle01")
    public String handle01(Map<String, String> map) {
        map.put("msg", "吃了吗?");
        int i = 1 / 0;
        return "success";
    }

    @ExceptionHandler(value = ArithmeticException.class)
    public void handlerException1() {
        System.out.println("算术异常了");
    }
}

将错误信息带出去:

    @ExceptionHandler(value = ArithmeticException.class)
    public ModelAndView handlerException1(Exception ex) {
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("error400");
        modelAndView.addObject("ex",ex);//将错误信息带出去
        return modelAndView;
    }
3. 写一个异常类用ControllerAdvice作为全局异常处理类
@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler
    public ModelAndView handle01(Exception ex){
        System.out.println("handle01:"+ex.getMessage());
        return new ModelAndView("error400");
    }
}

4. 优先级

如果同时有全局异常处理类和局部异常处理方法,那么方法优先,要是配置了handlerExceptionResolver,那么它的优先级最高

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值