Loading

Restful风格响应

@ApiModel("当前时间")
public class RestResponse<T> {

    @ApiModelProperty(value = "是否成功")
    private boolean success;

    @ApiModelProperty(value = "成功或者失败的code")
    private String code;

    @ApiModelProperty(value = "错误信息")
    private String errorMessage;

    @ApiModelProperty(value = "返回数据")
    private T data;

    @ApiModelProperty(value = "当前时间")
    private long currentTime;

    /**
     * 成功
     */
    private final static RestResponse RENDER_SUCCESS = new RestResponse(true, "0000");

    public RestResponse() {
        this.currentTime = SystemClock.now();
    }

    public RestResponse(boolean success, String code) {
        this.success = success;
        this.code = code;
        this.currentTime = SystemClock.now();
    }

    public RestResponse(boolean success, String code, String errorMessage, T data) {
        this.success = success;
        this.code = code;
        this.errorMessage = errorMessage;
        this.data = data;
        this.currentTime = SystemClock.now();
    }

    /**
     * 返回成功
     */
    public static RestResponse renderSuccess(){
        return RENDER_SUCCESS;
    }

    /**
     * 返回成功,带数据
     */
    public static <T> RestResponse<T> renderSuccess(T data){
        return new RestResponse<>(true, "0000", null, data);
    }

    /**
     * 返回失败
     */
    public static <T> RestResponse<T> renderError(ErrorEnum error){
        return new RestResponse<>(false, error.getCode(), error.getErrorMessage(), null);
    }

    /**
     * 返回失败,自定义错误信息
     */
    public static <T> RestResponse<T> renderError(String code, String errorMessage){
        return new RestResponse<>(false, code, errorMessage, null);
    }

    public boolean isSuccess() {
        return success;
    }

    public RestResponse<T> setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    public String getCode() {
        return code;
    }

    public RestResponse<T> setCode(String code) {
        this.code = code;
        return this;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public RestResponse<T> setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
        return this;
    }

    public T getData() {
        return data;
    }

    public RestResponse<T> setData(T data) {
        this.data = data;
        return this;
    }

    public Timestamp getCurrentTime() {
        return new Timestamp(currentTime);
    }

    public void setCurrentTime(long currentTime) {
        this.currentTime = currentTime;
    }
}
posted @ 2022-12-13 11:07  IamHzc  阅读(36)  评论(0编辑  收藏  举报