簡體   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