互聯網公司接口統一返回

互聯網公司接口統一返回

前言

博客書

版本說明

spring-boot=2.2.5.RELEASE

相關鏈接

  • lombok 官網:https://projectlombok.org/

接口統一返回

CommonResponse

package top.simba1949.response;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @Author Theodore
 * @Date 2020/3/20 15:55
 */
@Data
@AllArgsConstructor
public class CommonResponse {

    /** 請求結果 */
    private Boolean status;
    /** 錯誤碼,當 status=false 時,需要設置 */
    private ErrorCode errorCode;
    /** 信息,當 status=false 時,存儲錯誤信息;也可以存儲其他信息 */
    private String message;
    /** 返回數據 */
    private Object data;
}

ErrorCode

package top.simba1949.response;

/**
 * @Author Theodore
 * @Date 2020/3/20 16:14
 */
public enum ErrorCode {

    SYSTEM_SUCCESS("0000000", "成功"),
    SYSTEM_FAILURE("0000001", "系統異常")
    ;

    private String code;
    private String message;

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

ResponseBuilder

package top.simba1949.response;

/**
 * @Author Theodore
 * @Date 2020/3/20 16:40
 */
public class ResponseBuilder {
    /**
     * 成功:無數據返回
     * @return
     */
    public static CommonResponse buildSuccess(){
        return new CommonResponse(true, null, null, null);
    }

    /**
     * 成功:有數據返回
     * @param data
     * @return
     */
    public static CommonResponse buildSuccess(Object data){
        return new CommonResponse(true, null, null, data);
    }

    /**
     * 失敗:無數據返回
     * @param errorCode
     * @param message
     * @return
     */
    public static CommonResponse buildFailure(ErrorCode errorCode, String message){
        return new CommonResponse(false, errorCode, message, null);
    }

    /**
     * 失敗:有數據返回
     * @param errorCode
     * @param message
     * @param data
     * @return
     */
    public static CommonResponse buildFailure(ErrorCode errorCode, String message, Object data){
        return new CommonResponse(false, errorCode, message, data);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章