Java API统一返回Response格式

1、返回结果类

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
 * @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、错误代码

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * @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、返回数据接口

1
2
3
4
5
/**
 * @author Nick Tan
 */public interface Response {
 
}

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

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

发表评论

欢迎阅读『Java API统一返回Response格式|Java、开发语言、框架算法|Nick Tan-梓潼Blog』