本篇文章给大家带来的内容是关于api返回值的标准化的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
api返回值的标准化
例如
{"status":200,"message":"操作成功","data":"{\"id\":1,\"name\":\"张三\"}"}对象被封装在base.util.ResponseUtils类型下,返回值是标准的ResponseEntity对象,返回体
进行了二次封装,主要有status,messsage和data组成,返回方法有ok和okMessage,如果
真是返回消息,不需要对象,可以选择使用okMessage,反之使用ok方法。
封装的返回对象:
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
static class ResponseBody {
private int status;
private String message;
private Object data;
}对于http error来说有很多种,基本可以定为code在400到500之间的,像客户端参数问题就是400- bad request,而没有认证就是401-Unauthorized,认证但没有对应的权限就是403-Forbidden,请求的
资源没有发现就是404-Not Found,请求方式错误(方法是post,你发起请求用了get)就是405- Method Not Allowed等。
@GetMapping(GET_HTTP_ERROR)
ResponseEntity<?> getHttpError() throws IOException {
return ResponseEntity.badRequest().build();
}
@Test
public void getHttpError() throws Exception {
mockMvc
.perform(
get(LindDemo.GET_HTTP_ERROR)
.accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().is(400));
}响应的结果
MockHttpServletResponse:
Status = 400
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = [] @GetMapping(GET_ERROR)
ResponseEntity<?> getError() throws IOException {
return ResponseUtils.badRequest("传入的参数非法!");
}
@Test
public void getError() throws Exception {
mockMvc
.perform(
get(LindDemo.GET_ERROR)
.accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}响应的结果
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"status":400,"message":"传入的参数非法!","data":{}}
Forwarded URL = null
Redirected URL = null
Cookies = []通过上面的响应结果可以看到,我们封装的请求httpcode还是200,只不过把请求错误400状态码写在了body
对象里,目前这种方法用的比较多,像一些第三方接口用的都是这种方式,他们会规定相应的响应规范。
事实上,两种响应体都没有问题,关键在于开发之间的规则要确定,不要在项目里两者兼用!
以上就是api返回值的标准化的介绍(代码示例)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号