Java API统一返回Response格式

1、返回结果类

/**
 * @author Nick Tan
 */public class Result {

    private int status = ResultEnum.SUCCESS.getCode();

    private String message = ResultEnum.SUCCESS.getMessage();

    private Response data;

    public static Result instance(int code, String message, Response data) {
        return new Result(code, message, data);
    }

    public static Result instance(Response data) {
        return new Result(data);
    }

    public static Result instance() {
        return new Result();
    }

    public Result() {
    }

    public Result(int status, String message, Response data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    public Result(Response data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

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

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Response getData() {
        return data;
    }

    public void setData(Response data) {
        this.data = data;
    }
}

2、错误代码

/**
 * @author Nick Tan
 */public enum ResultEnum {

    /**
     * 200: 成功
     */    SUCCESS(200, "成功"),
    /**
     * 404: 不存在
     */    NOT_FOUND(404, "资源不存在"),
   
    /**
     * 403: 无权限
     */    FORBIDDEN(403, "没有权限访问"),
    /**
     * 400: 参数错误
     */    INVALID_REQUEST(400, "Invalid Request"),
    PARAM_ERROR(400, "请求参数错误"),
    TOKEN_ERROR(400, "请求签名错误"),
    /**
     * 405: 请求方式不支持
     */    METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
    /**
     * 406
     */    NOT_ACCEPTABLE(406, "Not Acceptable"),
    /**
     * 500
     */    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    /**
     * 999: 未知异常
     */    UNKNOW_ERROR(999, "未知错误");

    private int code;

    private String message;

    private ResultEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

3、返回数据接口

/**
 * @author Nick Tan
 */public interface Response {

}

1人评论了“Java API统一返回Response格式”

  1. Pingback: SpringBoot中使用RestControllerAdvice进行统一异常拦截 – 梓潼

发表评论