我目前正在一個代碼庫中作業,其中對于每個 REST API 回應,他們都使用如下所示的 Java 類
{
Object payload;
List<Error> errors;
String responseStatus;
}
問題是,當我們參考 REST API 的 swagger 檔案時,它顯示了如下所示的 json 結構。
{
"payload":{},
"errors": [
{
"errMsg":"",
"errCode": ""
}
],
"responseStatus":""
}
因此,如果回應成功,則回應將具有有效負載,錯誤時的錯誤串列和回應狀態分別設定為成功或失敗。
- 對錯誤和成功使用相同的 json 結構是一個好習慣嗎?
- 有什么方法可以改進 swagger 檔案,以便我可以顯示特定 API 回應的回應有效負載 json 的外觀。
編輯:我只想提一下,我不能將回應負載更改為任何其他內容,因為它被用于 1000 多個 API 并分發到不同的服務中。
有沒有辦法至少改進swagger檔案,而無需更改java中的回應物件,因為那艘船很久以前就已經航行了。
uj5u.com熱心網友回復:
- 對錯誤和成功回應使用相同的 json 結構不是一個好習慣。
- 是的,如果您可以控制 Swagger 定義,則可以為每個回應代碼指定不同的回應。
這是Swagger 檔案中的一個示例
paths:
/users/{id}:
get:
summary: Gets a user by ID.
response:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'401':
$ref: '#/components/responses/Unauthorized'
'404':
$ref: '#/components/responses/NotFound'
# Descriptions of common components
components:
responses:
NotFound:
description: The specified resource was not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
Unauthorized:
description: Unauthorized
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
schemas:
# Schema for error response body
Error:
type: object
properties:
code:
type: string
message:
type: string
required:
- code
- message
# Schema for the User response
User:
type: object
properties:
# Add properties for the User object
# ...
uj5u.com熱心網友回復:
您可以ResponseEntity<? extends Response>在方法中使用回傳型別。這樣如果回應成功,它們都回傳,回應是錯誤。
public ResponseEntity<? extends ResponseDto> foo(RequestDto request){
if(success){
return new ResponseEntity<>(new SuccessResponse(Enum.SuccessResponse.getMessage,200,dto),HttpStatus.OK);
}
return new ResponseEntity<>(new ErrorResponse(Enum.ErrorResponse.getMessage,400),HttpStatus.BAD_REQUEST);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/386884.html
