111
k94314517
2024-03-14 cb96c5493ebbb0767cf4d5b83544e131294225cb
1
2
3
4
5
6
7
8
9
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.doumee.core.model;
 
import com.doumee.core.constants.ResponseStatus;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.http.HttpStatus;
 
import java.io.Serializable;
 
/**
 * 接口返回对象
 * @author Eva.Caesar Liu
 * @date 2023/02/14 11:14
 */
@ApiModel("响应对象")
@Data
@AllArgsConstructor
public class ApiResponse<T> implements Serializable {
 
    @ApiModelProperty(value = "响应码")
    private int code;
 
    @ApiModelProperty(value = "请求是否成功")
    private boolean success;
 
    @ApiModelProperty(value = "错误消息")
    private String message;
 
    @ApiModelProperty(value = "数据")
    private T data;
 
    @ApiModelProperty(value = "异常消息")
    private String exception;
 
    public ApiResponse () {}
 
    /**
     * 请求成功
     */
    public static <T> ApiResponse<T> success(T data) {
        return ApiResponse.success("请求成功", data);
    }
 
    /**
     * 请求成功
     */
    public static <T> ApiResponse<T> success(String message, T data) {
        return new ApiResponse<>(HttpStatus.OK.value(), Boolean.TRUE, message, data, null);
    }
 
    /**
     * 请求失败
     */
    public static <T> ApiResponse<T> failed(String message) {
        return ApiResponse.failed(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
    }
 
    /**
     * 请求失败
     */
    public static <T> ApiResponse<T> failed(ResponseStatus status) {
        return ApiResponse.failed(status.getCode(), status.getMessage());
    }
 
    /**
     * 请求失败
     */
    public static <T> ApiResponse<T> failed(ResponseStatus status, Throwable ex) {
        return ApiResponse.failed(status.getCode(), status.getMessage(), ex);
    }
 
    /**
     * 请求失败
     */
    public static <T> ApiResponse<T> failed(Integer code, String message) {
        return ApiResponse.failed(code, message, null);
    }
 
    /**
     * 请求失败
     */
    public static <T> ApiResponse<T> failed(Integer code, String message, Throwable ex) {
        if (ex == null) {
            return new ApiResponse<>(code, Boolean.FALSE, message, null, null);
        }
        // 处理异常栈,防止过多内容导致响应内容过大
        StackTraceElement[] trace = ex.getStackTrace();
        StringBuilder exceptionStack = new StringBuilder(ex + "\n");
        for (StackTraceElement traceElement : trace) {
            exceptionStack.append("\tat ").append(traceElement).append("\n");
            if (exceptionStack.length() > 5000) {
                break;
            }
        }
        return new ApiResponse<>(code, Boolean.FALSE, message, null, exceptionStack.toString());
    }
}