首页 > 编程语言 >通用返回类设计(Java)

通用返回类设计(Java)

时间:2022-10-03 11:34:36浏览次数:52  
标签:返回 code 通用 String BaseResponse Java message public description

通用返回类

一般后端需要将数据封装成通用返回类再传递给前端

/**
 * 通用返回类
 * @param <T>
 */
@Data
public class BaseResponse<T> implements Serializable {
    //状态码
    private int code;
    //数据
    private T data;
    //状态码信息
    private String message;
    //状态码描述
    private String description;

    public BaseResponse(int code, T data, String message,String description) {
        this.code = code;
        this.data = data;
        this.message = message;
        this.description = description;
    }

    public BaseResponse(int code, T data,String message) {
        this(code,data,"","");
    }
    public BaseResponse(int code, T data) {
        this(code,data,"","");
    }
    public BaseResponse(ErrorCode errorCode) {
        this(errorCode.getCode(),null,errorCode.getMessage(),errorCode.getDescription());
    }
}

返回工具类,定义成功/失败方法

/**
 * 返回工具类
 */
public class ResultUtils {
    /**
     * 成功
     * @param data
     * @return
     */
    public static <T> BaseResponse<T> success(T data){
        return new BaseResponse<>(0,data,"ok");
    }

    /**
     * 失败
     * @param errorCode
     * @return
     */
    public static  BaseResponse error(ErrorCode errorCode){
        return new BaseResponse<>(errorCode);
    }
    public static BaseResponse error(ErrorCode errorCode,String message,String description){
        return new BaseResponse<>(errorCode.getCode(),message,description);
    }
    public static BaseResponse error(int code,String message,String description){
        return new BaseResponse<>(code,null,message,description);
    }
    public static BaseResponse error(ErrorCode errorCode,String description){
        return new BaseResponse<>(errorCode.getCode(),errorCode.getMessage(),description);
    }
}

用枚举定义错误码,统一成功/失败的信息

/**
 * 错误码
 */
public enum ErrorCode {
    /**
     * 返回异常枚举类
     */
    SUCCESS(0, "OK", ""),
    PARAMS_ERROR(40000, "请求参数错误", ""),
    NULL_ERROR(40001, "请求数据为空", ""),
    NOT_LOGIN(40100, "未登录", ""),
    NO_AUTH(40101, "无权限", ""),
    SYSTEM_ERROR(50000, "系统内部异常", "");
    /**
     * 状态码
     */
    private int code;
    /**
     * 状态码信息
     */
    private String message;
    /**
     * 状态码描述(详情)
     */
    private String description;

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public String getDescription() {
        return description;
    }

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

标签:返回,code,通用,String,BaseResponse,Java,message,public,description
From: https://www.cnblogs.com/galo/p/16750200.html

相关文章