其他分享
首页 > 其他分享> > 统一返回值

统一返回值

作者:互联网

RestResult

import lombok.Data;

@Data
public class RestResult<T> {

    private Integer code;

    private String message;

    private T data;



    public static RestResult success() {
        RestResult message = new RestResult();
        message.setCode(ResultCodeEnum.SUCCESS.getIntValue());
        message.setMessage(ResultCodeEnum.SUCCESS.getMessage());
        return message;
    }

    public static <T> RestResult<T> success(T data) {
        RestResult<T> message = new RestResult<>();
        message.setCode(ResultCodeEnum.SUCCESS.getIntValue());
        message.setMessage(ResultCodeEnum.SUCCESS.getMessage());
        message.setData(data);
        return message;
    }

    public static RestResult fail() {
        RestResult r = new RestResult();
        r.setCode(ResultCodeEnum.ERROR.getIntValue());
        r.setMessage(ResultCodeEnum.ERROR.getMessage());
        return r;
    }

    public static RestResult fail(String error) {
        RestResult r = new RestResult();
        r.setCode(ResultCodeEnum.ERROR.getIntValue());
        r.setMessage(error);
        return r;
    }

    public static RestResult fail(int code,String errMessage) {
        RestResult restResult = new RestResult();
        restResult.setCode(code);
        restResult.setMessage(errMessage);
        return restResult;
    }


    public static RestResult setResult(ResultCodeEnum result) {
        RestResult r = new RestResult();
        r.setCode(result.getIntValue());
        r.setMessage(result.getMessage());
        return r;
    }


    public RestResult message(String message) {
        this.setMessage(message);
        return this;
    }

    public RestResult code(Integer code) {
        this.setCode(code);
        return this;
    }


    public RestResult data(T param) {
        this.setData(param);
        return this;
    }
}

ResultCodeEnum

@Getter
public enum ResultCodeEnum {

    SUCCESS(1,"成功"),
    ERROR(0, "失败"),
    UNKNOWN_ERROR(-1, "未知错误"),
    PARAM_ERROR(-2, "参数错误"),
    NULL_POINT(-3, "空指针异常"),
    INDEX_OUT_OF_BOUNDS(-4, "下标越界异常"),
    REQUEST_TIMEOUT(-5, "请求超时"),
    NOT_LOGIN_ERROR(-6, "未登录异常");

    private int intValue;

    private String message;


    ResultCodeEnum(int code, String message) {
        this.intValue = code;
        this.message = message;
    }
}

 

 

标签:code,return,ResultCodeEnum,RestResult,返回值,message,public,统一
来源: https://www.cnblogs.com/JYB2021/p/16690904.html