linzhijie
2021-03-11 93af1c6ffb9ae0e894689ad3a37b548e57d54cff
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
package com.ots.project.exam.dto;
 
import com.ots.common.enums.ResponseCode;
import com.ots.common.enums.SystemCode;
import com.ots.project.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
 
/**
 * @author Shawn
 */
@Slf4j
public class RestResponse<T> {
    private int code;
    private String message;
    private T response;
 
    public RestResponse(int code, String message) {
        this.code = code;
        this.message = message;
    }
 
    public RestResponse(int code, String message, T response) {
        this.code = code;
        this.message = message;
        this.response = response;
    }
 
    public static RestResponse fail(Integer code, String msg) {
        return new RestResponse<>(code, msg);
    }
 
    /**
     * 增加错误编码统一处理
     *
     * @param enumCode
     * @return
     */
    public static RestResponse fail(ResponseCode enumCode) {
        return new RestResponse<>(enumCode.getCode(), enumCode.getMessage());
    }
 
    /**
     * 异常结合枚举方便异常统一处理
     *
     * @param e
     * @return
     */
    public static RestResponse fail(Exception e) {
        if (e instanceof BaseException) {
            BaseException e1 = (BaseException) e;
            return new RestResponse<>(e1.getResponseEnum().getCode(), e1.getMessage());
        } else if (e instanceof DuplicateKeyException) {
            log.error("DuplicateKeyException:", e);
            return new RestResponse<>(998, "复合索引冲突,数据不能重复提交!");
        } else {
            return new RestResponse<>(999, e.getMessage());
        }
    }
 
    public static RestResponse ok() {
        SystemCode systemCode = SystemCode.OK;
        return new RestResponse<>(systemCode.getCode(), systemCode.getMessage());
    }
 
    public static <F> RestResponse<F> ok(F response) {
        SystemCode systemCode = SystemCode.OK;
        return new RestResponse<>(systemCode.getCode(), systemCode.getMessage(), response);
    }
 
    public int getCode() {
        return code;
    }
 
    public void setCode(int code) {
        this.code = code;
    }
 
    public String getMessage() {
        return message;
    }
 
    public void setMessage(String message) {
        this.message = message;
    }
 
    public T getResponse() {
        return response;
    }
 
    public void setResponse(T response) {
        this.response = response;
    }
}