springboot统一异常处理

我们不需要再代码中存在trycatch语句,

只需要将可能发生的异常全部抛出,由异常拦截器统一处理。 

创建exception包

创建自定义的异常类型

AppException

public class AppException extends RuntimeException{

    private final int code ;
    private final String msg ;


    public AppException(AppExceptionCodeMsg appExceptionCodeMsg){
        super();
        this.code = appExceptionCodeMsg.getCode();
        this.msg = appExceptionCodeMsg.getMsg();

    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

} 

创建跟业务相关的异常返回枚举类

AppExceptionCodeMsg  

public enum AppExceptionCodeMsg {
    /**
     *
     */
    INVALID_CODE(10000,"验证码无效"),
    /**
     *
     */
    USERNAME_NOT_EXISTS(10001,"用户名不存在"),
    /**
     *
     */
    USER_CREDIT_NOT_ENOUTH(10002,"用户积分不足");

    private final int code ;
    private final String msg ;

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }


    AppExceptionCodeMsg(int code, String msg){
        this.code = code;
        this.msg = msg;
    }

 

定义异常拦截器 

@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public R exceptionHandler(Exception e){
        //这里先判断拦截到的Exception是不是我们自定义的异常类型
        if(e instanceof AppException appException){
            return R.error(appException.getCode(),appException.getMsg());
        }
        //如果拦截的异常不是我们自定义的异常(例如:数据库主键冲突)
        return R.error();
    }
}

 

附加统一消息返回模板

R

public class R extends HashMap {
    @Serial
    private static final long serialVersionUID = 1L;

    public R() {
        put("code", 200);
        put("msg", "操作成功");
    }



    public static R error(String msg) {
        return error(500, msg);
    }

    public static R error() {
        return error(500, "未知异常,请联系管理员");
    }


    public static R error(int code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }



    public static R ok(Object object) {
        R r = new R();
        r.put("data", object);
        return r;
    }

    public static R ok(String msg,Object object) {
        R r = new R();
        r.put("msg", msg);
        r.put("data", object);
        return r;
    }

    public static R ok(Map map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }

    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}

 

你可能感兴趣的:(springBoot,小技术帮助,spring,boot,java,后端)