SpringMvc异常处理器

1、异常分类

大体上分为三种:

        1、用户操作引起的异常,如应该输入整型数据结果输入了字符串

        2、系统产生的异常,服务器出问题了

        3、其他异常,如代码有bug

2、编写异常处理器

需要在类的上面加上注解@RestControllerAdvice,意为 声明一个类做欸异常处理器类 在处理异常的方法的上面加上注解@ExceptionHandler(),括号里填需要处理的异常的类型,意为 处理什么类型的异常

@RestControllerAdvice 
public class ProjectExceptionAdvice { 
    @ExceptionHandler(Exception.class) 
    public Result doException(Exception ex){ 
        return new Result(0000,null,"出现异常"); 
    }
}

注解@RestControllerAdvice 表示声明这个类为异常处理器类

注解@ExceptionHandler(Exception.class) 表示这是一个处理异常的方法,参数为异常的类型

3、编写异常分类处理

系统异常

public class SystemException extends RuntimeException {
    private Integer code;

    public void setCode(Integer code) {
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public SystemException(Integer code, String message) {
        super(message);
        this.code=code;
    }

    public SystemException(Integer code,String message, Throwable cause) {
        super(message, cause);
        this.code=code;
    }
}

用户异常

public class BusinessException extends RuntimeException {
    private Integer code;

    public void setCode(Integer code) {
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public BusinessException(Integer code, String message) {
        super(message);
        this.code=code;
    }

    public BusinessException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code=code;
    }
}

继承RuntimeException的作用是出现异常后不处理,直接抛出

4、修改异常处理器

@RestControllerAdvice
public class ProjectExceptionAdvice {

//    处理系统异常
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex){
//        记录日志
//        发送短信给开发人员
//        发送短信给运维人员
        return new Result(ex.getCode(),null,ex.getMessage());
    }

//    处理用户产生的异常
    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex){
        return new Result(ex.getCode(),null,ex.getMessage());
    }

//    处理其他异常
    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex){
//        记录日志
//        发送短信给开发人员
//        发送短信给程序员
        return new Result(Code.noKnow_exception,null,"系统出现错误,请稍后再试");
    }
}

莫愁千里路,自有到来风

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

{春树樱良}

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值