1 package cn.itcast.order.service;
2
3 import org.springframework.http.HttpStatus;
4 import java.time.LocalDateTime;
5
6 /**
7 * 通用Rest接口结果类
8 */
9 public class RestResult {
10
11 private final Integer code;
12 private final String msg;
13 private final Object data;
14 private final LocalDateTime timestamp = LocalDateTime.now();
15
16 /* 常用静态字段 */
17 public static final RestResult SUCCESS = new RestResult(HttpStatus.OK);
18 public static final RestResult FAIL = new RestResult(HttpStatus.INTERNAL_SERVER_ERROR);
19
20 /* 常用静态方法 */
21 public static RestResult success(Object data) {
22 return new RestResult(HttpStatus.OK, data);
23 }
24
25 public static RestResult fail(String msg) {
26 return new RestResult(500, msg);
27 }
28
29 /* 构造方法 */
30 public RestResult(Integer code, String msg, Object data) {
31 this.code = code;
32 this.msg = msg;
33 this.data = data;
34 }
35
36 public RestResult(Integer code, String msg) {
37 this(code, msg, null);
38 }
39
40 public RestResult(HttpStatus httpStatus) {
41 this(httpStatus.value(), httpStatus.getReasonPhrase());
42 }
43
44 public RestResult(HttpStatus httpStatus, Object data) {
45 this(httpStatus.value(), httpStatus.getReasonPhrase(), data);
46 }
47
48 /* Getter */
49 public Integer getCode() {
50 return code;
51 }
52
53 public String getMsg() {
54 return msg;
55 }
56
57 public Object getData() {
58 return data;
59 }
60
61 public LocalDateTime getTimestamp() {
62 return timestamp;
63 }
64
65 @Override
66 public String toString() {
67 return "Resullt{" +
68 "code=" + code +
69 ", msg='" + msg + '\'' +
70 ", data=" + data +
71 ", timestamp=" + timestamp +
72 '}';
73 }
74 }