自定义异常

一. 异常使用的枚举类

@Getter
public enum HttpStatusEnums {
    /**
     * 响应成功状态码
     */
    SUCCESS(HttpStatus.OK.value(), "成功"),

    /**
     * 身份异常
     */
    TOKEN_ERR(401,"token 验证失败,请重新登录"),

    /**
     * 系统级错误
     * code 1010xx
     */
    SYS_ERR_OUT_OF_HEAP(101001, "堆内存溢出"),

    /**
     * 服务级错误
     * code 1020xx
     */
    SER_ERR_DATA_INCONSISTENT(102001, "系统内数据不一致异常"),

    /**
     * 客户端错误
     * code 1021xx
     */
    CLI_ERR_TOKEN_NULL(102101, "token 不可为空"),

    /**
     * 通用异常校验
     * code 1030xx
     */
    CLI_ERR_EMPTY_PARAM(103001, "请求参数:%s 不可为空"),
    CLI_ERR_ZERO_ASSIGN_PARAM(103002,"ID不可为0"),
    CLI_ERR_HEADER_PARAM(103004,"缺少Header参数:%s"),
    CLI_ERR_GENERAL_TIPS(103005,"%s"),


    ;
    /**
     * 错误编码
     */
    private final int code;

    /**
     * 错误描述
     */
    private final String msg;

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

二. 自定义客户端异常类,后续会针对此类进行异常抛出

@Getter
public class ClientException extends RuntimeException{
    /**
     * 异常编码
     */
    private final int code;

    /**
     * 错误描述
     */
    private final String msg;

    public BaseException(int code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    public BaseException(HttpStatusEnums httpStatusEnums) {
        super(httpStatusEnums.getMsg());
        this.code = httpStatusEnums.getCode();
        this.msg = httpStatusEnums.getMsg();
    }

    public BaseException(HttpStatusEnums httpStatusEnums,String msg) {
        super(String.format(httpStatusEnums.getMsg(), msg));
        this.code = httpStatusEnums.getCode();
        this.msg = String.format(httpStatusEnums.getMsg(), msg);
    }
}

2.1 实际的使用

// 参数不可为空的异常抛出,
throw new ClientException(HttpStatusEnums.CLI_ERR_EMPTY_PARAM.getCode(),
                    String.format(HttpStatusEnums.CLI_ERR_EMPTY_PARAM.getMsg(), msg));

三. 自定义服务端异常类,此类异常在控制台打印,不返回给客户端,产生异常时客户端只能看到500字样

@Getter
public class ServerException extends RuntimeException{
    /**
     * 异常编码
     */
    private final int code;

    /**
     * 错误描述
     */
    private final String msg;

    public BaseException(int code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    public BaseException(HttpStatusEnums httpStatusEnums) {
        super(httpStatusEnums.getMsg());
        this.code = httpStatusEnums.getCode();
        this.msg = httpStatusEnums.getMsg();
    }

    public BaseException(HttpStatusEnums httpStatusEnums,String msg) {
        super(String.format(httpStatusEnums.getMsg(), msg));
        this.code = httpStatusEnums.getCode();
        this.msg = String.format(httpStatusEnums.getMsg(), msg);
    }
}

3.1 实际的使用

// 参数不可为空的异常抛出,
throw new ServerException(HttpStatusEnums.CLI_ERR_EMPTY_PARAM.getCode(),
                    String.format(HttpStatusEnums.CLI_ERR_EMPTY_PARAM.getMsg(), msg));