自定义程序返回异常

2019-08-16  本文已影响0人  firefly_

throw new AppException(ErrorCode.INVALID_PARAMS, "验证码错误");


public class AppException extends RuntimeException {
    private static final long serialVersionUID = 2404372373182554123L;
    private int code;
    private String msg;
    private Object data;

    public AppException() {
        this(ErrorCode.UNKNOW_EXCEPTION);
    }

    public AppException(ErrorInterface code) {
        ErrorInterface code = code == null ? Error.UNKNOW_EXCEPTION : code;
        this.code = ((ErrorInterface)code).getCode();
        this.msg = ((ErrorInterface)code).getMsg();
    }

    public AppException(ErrorInterface code, Exception e) {
        this(code);
        this.addSuppressed(e);
    }

    public AppException(ErrorInterface code, String exMsg) {
        this(code);
        this.msg = String.format(code.getMsg(), exMsg);
    }

    public AppException(ErrorInterface code, String exMsg, Object data) {
        this(code);
        this.msg = String.format(code.getMsg(), exMsg);
        this.data = data;
    }

    public AppException(int code, String exMsg) {
        this.code = code;
        this.msg = exMsg;
    }

    public AppException(int code, String exMsg, Object data) {
        this.code = code;
        this.msg = exMsg;
        this.data = data;
    }

    public String getMessage() {
        return this.msg;
    }

    public int getCode() {
        return this.code;
    }

    public Object getData() {
        return this.data;
    }
}

public interface ErrorInterface {
    String getMsg();

    int getCode();
}

public enum ErrorCode implements ErrorInterface {
    UNKNOW_EXCEPTION(60013, "未知异常~"),
    INIT_FAILED(20004, "Init failed, %s"),
    NOT_ALLOW_MODIFY(20005, "Not Allow Modify, %s"),
    INTERFACE_ERROR(21000, "%s"),
    INVALID_PARAMS(21001, "%s"),
    
    ;

    private int code;
    private String msg;

    ErrorCode(int code) {
        this.code = code;
        this.msg = this.name();
    }

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

    @Override
    public String getMsg() {
        return this.msg;
    }

    @Override
    public int getCode() {
        return this.code;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读