全局异常处理

一.编写一个全局异常类

public class GlobalException extends RuntimeException{

    /**
     * 错误对象
     * @param message
     */
    public GlobalException(String message){
        super(message);
    }
}

二.编写全局异常处理类

/**
 * 全局异常处理
 */
//@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {

    //拦截异常 : 这个注解就可以拦截器 GlobalException 异常
    @ExceptionHandler(GlobalException.class)
    public JSONResult globalException(GlobalException e){
        e.printStackTrace();
        return JSONResult.error(e.getMessage());
        
    }


    //拦截器其他异常
    @ExceptionHandler(Exception.class)
    public JSONResult exception(Exception e){
        e.printStackTrace();
        return JSONResult.error(ErrorCode.SYSTEM_ERROR.getMessage(),ErrorCode.SYSTEM_ERROR.getCode());
    }

}

这里使用的是web项目的注解需要导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

三.为了扩展性更好编写枚举类保存错误码

/** 系统错误码 **/
public enum ErrorCode {

    SYSTEM_ERROR("500","系统内部异常");

    //错误码
    private String code;
    //错误信息
    private String message;

    ErrorCode(String code, String message) {
        this.code = code;
        this.message = message;
    }

    public String getCode() {
        return code;
    }
    public String getMessage() {
        return message+"["+code+"]";
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值