linzhijie
2021-03-08 d26f0e81960986cef39db408440bbc3d0c56a853
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
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;
 
@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);
    }
    
    public static RestResponse fail(ResponseCode enumCode) {
        return new RestResponse<>(enumCode.getCode(), enumCode.getMessage());
    }
    
    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;
    }
}