繁体   English   中英

在 Spring 引导中返回每个 API 的统一响应的最佳方法是什么?

[英]What is the best way to return the uniform response for each API in Spring Boot?

我想知道为每个 API 返回统一响应的最佳方法。 例如:

如果成功,它应该响应:

{
  statusCode: 200,
  message: "customMessage",
  results: [{...}]
}

如果失败,它应该响应(例如):

{
  statusCode: 404,
  message: "customMessage",
  results: []
}

使用ResponseBodyAdvice或更好地创建例如SuccessDTOErrorDTO并直接从每个 controller 方法返回是一个好主意。

如果这是最好的解决方案,我会欢迎ResponseBodyAdvice上的一些示例。

  1. 创建 SuccessDTO 并为所有成功场景返回它。

{

“数据”:{“名称”:“Ram”,“id”:“101”},“消息”:“已添加用户”,“状态”:200,“时间戳”:“2021-12-02T14: 51:35.733+00:00”,“路径”:“/api/v1/user/”

}

注意:- 数据字段将包含响应数据

  1. 创建 ErrorDTO 并返回失败/异常情况(最好使用 controller 建议)。

{

"message":"Not be able to add user"
"status":400
"timeStamp":"2021-12-02T14:51:35.733+00:00"
"path":""/api/v1/user/"

}

注意:如果出现错误/异常,将没有数据字段。

类似的详细信息可在以下链接中找到。

https://medium.com/codestorm/custom-json-response-with-responsentity-in-spring-boot-b09e87ab1f0a

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM