定义业务异常和返回结果

57 阅读1分钟
public class BizException extends RuntimeException {

    private int errorCode;
    private String errorMsg;
    
    public BizException() {
        super();
    }

    public BizException(String message) {
        super(message);
    }
    
    public BizException(int errorCode, String errorMsg) {
        super(errorMsg);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }
}
public class Result<T> {
    // 状态码
    private int code;
    // 返回信息
    private String message;
    // 返回的数据
    private T data;

    // 构造方法私有化,外部通过静态方法创建实例
    private Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    // 成功时调用的方法
    public static <T> Result<T> success(T data) {
        return new Result<>(200, "Success", data);
    }

    // 失败时调用的方法
    public static <T> Result<T> error(int code, String message) {
        return new Result<>(code, message, null);
    }
}