Spring-统一异常处理

统一异常处理

使用SpringMVC后,异常就不必在三层代码去处理了,而是直接抛给框架,框架会将所有的异常统一转交给我们自定义的统一异常处理类来处理。
SpringMVC支持下面两个注解来实现全局异常处理
​ @RestControllerAdvice 标注在类上,声明当前类是一个用于专门处理异常的类
​ @ExceptionHandler 标注在方法上,声明当前方法可以处理哪些异常

1. 模拟异常

    //模拟异常
    //http://localhost:8080/user/demo21?type=1
    @RequestMapping("/demo21")
    public void demo21(Integer type) {
        if (type == 1) {  //ArithmeticException
            int i = 1 / 0;
        } else if (type == 2) { //NullPointerException
            String s = null;
            System.out.println(s.length());
        } else {  //ArrayIndexOutOfBoundsException
            Integer[] arr = new Integer[2];
            arr[5] = 1;
        }
    }

2. 全局异常处理

//通用异常处理器,只要程序中出现异常,都会来到这个类中进行处理
@RestControllerAdvice //@RestControllerAdvice 标注在类上,声明当前类是一个用于专门处理异常的类
public class CommonExceptionHandler {

    //空指针异常
    @ExceptionHandler(NullPointerException.class) //标注在方法上,声明当前方法可以处理那些异常
    public String handlerNullPointerException(Exception e){
        //1.打印日志(程序员排错)
        e.printStackTrace();
        //2.返回错误
        return "NullPointerException";
    }

    //算术逻辑异常
    @ExceptionHandler(ArithmeticException.class)
    public String handlerArithmeticException(Exception e){
        //1.打印日志(程序员排错)
        e.printStackTrace();
        //2.返回错误
        return "ArithmeticException";
    }

    //数组角标越界异常
    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    public String handlerArrayIndexOutOfBoundsException(Exception e){
        //1.打印日志(程序员排错)
        e.printStackTrace();
        //2.返回错误
        return "ArrayIndexOutOfBoundsException";
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值