服务端统一返回格式

返回的 json 信息

  • 错误情况
1
2
3
4
{
"err_code": 1003,
"err_msg": "参数错误,超出最大数量限制"
}
  • 正常情况
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"err_code": 0,
"err_msg": "ok",
"data": {
"id": 1,
"name": "lyloou",
"email": "lyloou@qq.com",
"personal_signature": "多么美好的太阳",
"gmt_create": "2020-01-16T09:38:18.000+0000",
"gmt_modified": "2020-03-14T11:27:58.000+0000",
"is_disabled": false
}
}

具体实现

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
public class Result {

@JsonProperty("err_code")
private final int status;

@JsonProperty("err_msg")
private String msg;

@JsonProperty("data")
private Object data;

public Result(int status, String msg) {
this.status = status;
this.msg = msg;
}

public Result data(Object data) {
this.data = data;
return this;
}

public Result msg(String msg) {
this.msg = msg;
return this;
}

public Result appendMsg(String msg) {
return appendMsg(msg, ", ");
}

public Result appendMsg(String msg, String sep) {
if (!Strings.isNullOrEmpty(msg)) {
this.msg = Joiner.on(sep).join(this.msg, msg);
} else {
this.msg = msg;
}
return this;
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 处理 Result 的接口,具体实现看 ResultHandlerImpl
*/
public interface ResultHandler {

/**
* 只需要返回 code 和 msg
*
* @param code 状态码
* @return 结果
*/
Result msgResult(StatusCode code);

/**
* 正常返回时,才使用这个;
* 错误的时候,尽量不要用这个,除非前端有作处理。填写不当的 data,有可能会导致解析不对;
*
* @param code 错误码
* @param data 返回给调用者的数据
* @return 结果
*/
Result dataResult(StatusCode code, Object data);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Component
public class ResultHandlerImpl implements ResultHandler {

@Override
public Result msgResult(StatusCode code) {
StatusCodeDict status = code.get();
return new Result(status.code(), status.msg());
}


@Override
public Result dataResult(StatusCode code, Object data) {
StatusCodeDict status = code.get();
Result result = new Result(status.code(), status.msg());
result.data(data);
return result;
}

}
1
2
3
4
5
6
7
8
9
10
/**
* ResultHandle 用此类作为参数。
* 通过此接口,可以通过 lambda 的方式来获取 StatusCodeDict 里的信息
* (<code>resultHandler.msgResult(() -> PARAM_LOGIN_ERROR);</code>)
*/
@FunctionalInterface
public interface StatusCode extends Supplier<StatusCodeDict> {
@Override
StatusCodeDict get();
}
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
/**
* 错误码字典
*/
public enum StatusCodeDict {


// 通用码
COMMON_OK(0, "ok"),
COMMON_UNKNOWN(9999, "未知的异常"),
COMMON_INVALID_REQUEST(9998, "无效的请求"),

// 系统
SYSTEM_404(404, "404你懂的"),
SYSTEM_502(502, "服务器打洋了"),
SYSTEM_500(500, "哎哟,这里有个锅"),

PARAM(1001, "参数错误"),
PARAM_BEYOND_QUANTITY_NUMBER(1003, "参数错误,超出最大数量限制"),

// 登录
PARAM_LOGIN_ERROR(1102, "用户名不存在或密码错误"),

// 商品
GOODS_IS_NOT_EXISTED(1301, "商品不存在"),
GOODS_IS_NOT_MARKETABLE(1302, "商品已经下架"),

DB(1401, "数据库异常"),

UNDEFINED(1999, "未定义的业务异常"),
;


private int code;
private String msg;
private static final Map<Integer, StatusCodeDict> dict = new HashMap<>();

static {
Arrays.stream(StatusCodeDict.values())
.forEach(p -> dict.put(p.code, p));
}

public static StatusCodeDict of(int code) {
return Optional.of(dict.get(code)).orElse(COMMON_UNKNOWN);
}

StatusCodeDict(int code, String msg) {
this.code = code;
this.msg = msg;
}

public int code() {
return code;
}

public String msg() {
return msg;
}
}

调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@RestController
@RequestMapping(path = "${apiVersion}/user")
public class UserController {

@Autowired
private ResultHandler resultHandler;

@Autowired
UserMapper userMapper;

@PostMapping("login")
public Result login(
@RequestParam("name") String name,
@RequestParam("password") String password
) {
UserPassword userPassword = userMapper.getUserPasswordByNamePassword(name, password);
if (userPassword == null) {
return resultHandler.msgResult(() -> PARAM_LOGIN_ERROR);
}
User user = userMapper.getUser(userPassword.getUserId());
return resultHandler.dataResult(() -> COMMON_OK, user);
}
}