背景
在项目开发中,如果我们没有对参数做校验或对业务处理做判断,经常会将一串让人头大的错误信息抛给前端,用户体验直接下降到零,而且也会将一些关键信息暴露出去,造成不可估量的错误。
现在大多数项目都采用了微服务架构,前后端分离开发,项目复杂度高,前后端职责划分很清楚,如果没有响应数据随便定义,前端人员会疯掉的,而且也不利于我们后期排查错误。
现在大多数项目都用的是Spring框架,接下来我们将利用Spring框架来解决以上两个问题。
响应格式
@Data@ToStringpublic class Result implements Serializable { private int code; private String msg; private T bean; public static Result success() { return success(null); } public static Result success(T bean) { Result result = new Result<>(); result.code = ResultType.SUCCESS.getCode(); result.msg = ResultType.SUCCESS.getMsg(); result.bean = bean; return result; } public static Result fail(String msg) { return fail(ResultType.FAIL.getCode(), msg); } public static Result fail(String msg, T bean) { return fail(ResultType.FAIL.getCode(), msg, bean); } public static Result fail(ResultType resultCode) { return fail(resultCode.getCode(),resultCode.getMsg()); } public static Result fail(ResultType resultCode, T bean) { return fail(resultCode.getCode(), resultCode.getMsg(), bean); } public static Result fail(int code, String msg) { Result result = new Result<>(); result.code = code; result.msg = msg; return result; } public static Result fail(int code, String msg, T bean) { Result result = new Result<>(); result.code = code; result.msg = msg; result.bean = bean; return result; }}
开发过程中我们约定后端返给前端响应格式统一为JSON,如下所示:
{ "code": 10000, "msg