- 为什么需要将接口返回结构体统一
- 避免书写重复性的代码,方便团队合作,规范。
- 方便调用,直接调用工具类方法就可以。
- 统一输出,做到不管是发生异常,错误,还是正常返回。
- 确定结构体,包含code,msg,data三个成员,其中code是Integer类型代表错误码,msg是String类型代表错误提示,data是泛型T代表返回数据体,其中filedsName作用是替换占位符,可详细提示,代码如下:
``
@Getter
public class ResultBody<T> implements Serializable {
private Integer code;
private String msg;
@JsonInclude(JsonInclude.Include.NON_NULL)
private T data;
public ResultBody(ErrorCode code, String... filedsName) {
this.code = code.getCode();
this.msg = String.format(code.getMsg(), filedsName);
}
public ResultBody(ErrorCode code, T data, String... filedsName) {
this.code = code.getCode();
this.msg = String.format(code.getMsg(), filedsName);
this.data = data;
}
public ResultBody(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public ResultBody(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public ResultBody() {
}
}
- 错误码对象统一放在枚举类中,方便管理,可重复利用枚举类对象,包含两成员code,msg,其中code是Integer类型代表错误码,msg是String类型代表错误码详细信息,其结构如下:
``
@Getter
public enum ErrorCode {
/**
* 系统全局错误码 SYSTEM_SUCCESS
* 0、-1、404、500、403
*/
SUCCESS(0, "success"),
FAIL(-1, "fail"),
SYSTEM_ERROR_404(404, "Interface Not Found"),
SYSTEM_ERROR_500(500, "Interface %s internal error, please contact the administrator"),
SYSTEM_LANGUAGE_CODE_ERROR(600, "The language encoding is not supported by the system"),
ILLEGAL_PARAMETER(1000, "Illegal parameter"),
PARAM_NOT_EXIST(1001, "%s does not exist")
;
public Integer code;
public String msg;
ErrorCode(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
-
返回结构体工具类,供接口,统一异常,错误返回调用,其中错误码对象是静态导包,其代码如下:
``
public class ResultBodyUtil { public static ResultBody success() { return resultBody(SUCCESS); } public static <T> ResultBody success(T data) { return resultBody(SUCCESS, data); } public static ResultBody resultBody(ErrorCode errorCode, String... filedsName) { return new ResultBody(errorCode, filedsName); } public static <T> ResultBody resultBody(ErrorCode errorCode, T data, String... filedsName) { return new ResultBody(errorCode, data, filedsName); } public static ResultBody paramFail() { return resultBody(ILLEGAL_PARAMETER); } }
-
返回结构体使用,比如接口调用返回使用如下:
``
@PostMapping("/getToken")
public ResultBody getToken(HttpServletRequest request) {
String appid = (String) request.getAttribute("appId");
if (StringUtils.isEmpty(appid))
return ResultBodyUtil.resultBody(ErrorCode.PARAM_NOT_EXIST, "appId");
String tokenKey = String.format(ModuleConst.TOEKN_KEY, appid);
String token = Md5Util.md5Encode(appid + DateUtil.date2Str());
openAppService.updateTokenByAppId(appid, token);
redisUtil.setNX(tokenKey, token, ModuleConst.DEFAULT_KEY_LIVE_TIME);
Map<String, String> map = Maps.newHashMap();
map.put("token", token);
return ResultBodyUtil.success(map);
}