在开发 RestFul 风格 时,为了保持响应结构的一致性,公司内部一般都有标准化的响应格式。这不仅可以提高代码的可维护性,还可以帮助前端开发者更容易地处理和解析 API 响应。

通常的接口返参格式:

{
	"success": true,
	"data": null
}

上面是成功情况,下面是失败情况。

{
	"success": false,
	"errorCode": "10000",
	"message": "用户名不能为空"
}
  • message: 服务端响应消息,字符串类型,当 successfalse 时才会不为空,用于提示失败的原因,方便前端提示用户;
  • errorCode: 异常码,字符串类型,微服务中用的比较多,通常格式为服务的唯一标识 + 异常码进行返回,如 QMS100000, 这样做的好处是,当发生问题时,用于快速锁定是链路上的哪个服务出现了问题。因为本项目是单体项目,其实用处不大,小伙伴们知道有这样的规范就行;
  • message: 响应消息,当后端出现业务异常时,需明确告诉调用者问题原因,本项目中,是为了方便前端提示;

响应参数工具类

可以写一份静态类来根据具体的message,data封装一个json对象返回。

@Data
public class Response<T> implements Serializable {
 
    // 是否成功,默认为 true
    private boolean success = true;
    // 响应消息
    private String message;
    // 异常码
    private String errorCode;
    // 响应数据
    private T data;
 
    // =================================== 成功响应 ===================================
    public static <T> Response<T> success() {
        Response<T> response = new Response<>();
        return response;
    }
 
    public static <T> Response<T> success(T data) {
        Response<T> response = new Response<>();
        response.setData(data);
        return response;
    }
 
    // =================================== 失败响应 ===================================
    public static <T> Response<T> fail() {
        Response<T> response = new Response<>();
        response.setSuccess(false);
        return response;
    }
 
    public static <T> Response<T> fail(String errorMessage) {
        Response<T> response = new Response<>();
        response.setSuccess(false);
        response.setMessage(errorMessage);
        return response;
    }
 
    public static <T> Response<T> fail(String errorCode, String errorMessage) {
        Response<T> response = new Response<>();
        response.setSuccess(false);
        response.setErrorCode(errorCode);
        response.setMessage(errorMessage);
        return response;
    }
}

这样,在进行 @Validated SpringBoot赋能接口规则校验 时,就可以直接使用Response类来返回json对象给前端:

@PostMapping("/test")
@ApiOperationLog(description = "测试接口")
	public Response test(@RequestBody @Validated User user, BindingResult bindingResult) {
	// 是否存在校验错误
	if (bindingResult.hasErrors()) {
		// 获取校验不通过字段的提示信息
		String errorMsg = bindingResult.getFieldErrors()
				.stream()
				.map(FieldError::getDefaultMessage)
				.collect(Collectors.joining(", "));
 
		return Response.fail(errorMsg);
	}
 
	// 返参
	return Response.success();
}

省去 null 参数

在使用工具类的时候可以发现,success的结果哪怕没有data也会返回data,可以通过setting中的设置来改变后台返参,如果为null就直接省略:

jackson

spring:
  jackson:
    # 设置后台返参,若字段值为 null, 则不返回
    default-property-inclusion: non_null
    # 设置日期字段格式
    date-format: yyyy-MM-dd HH:mm:ss