如何在swagger codegen中处理多种响应/返回类型(204为空,400为非空等)?
Posted
技术标签:
【中文标题】如何在swagger codegen中处理多种响应/返回类型(204为空,400为非空等)?【英文标题】:How to handle multiple response/return types (empty for 204, non-empty for 400 etc) in swagger codegen? 【发布时间】:2020-06-05 02:09:39 【问题描述】:我使用的是 openapi 3.0.2 版。
我有以下描述我的回答的规范:
responses:
'201':
description:
Created
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: The resource could not be found.
'500':
description: The request failed due to an unexpected server error.
对于大多数响应代码,我不返回任何响应正文,但对于 400 响应 代码,我想返回Error对象:
Error:
type: object
properties:
code:
type: string
message:
type: string
required:
- code
- message
当我为此端点生成 Java 服务器代码时,方法的返回类型
是ResponseEntity<Void>
,意思是我不能返回Error对象?
似乎与这些问题类似:
https://groups.google.com/forum/#!topic/swagger-swaggersocket/ygVjA2m5gY0
https://github.com/swagger-api/swagger-codegen/issues/7743
https://github.com/swagger-api/swagger-codegen/issues/4398
我不知道这是否已经修复,或者是否有任何解决方法?
【问题讨论】:
【参考方案1】:我使用here 描述的以下方法来解决这个问题:
@Override
public ResponseEntity<Void> deleteThing(...)
try
myService.deleteThing(...);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
catch (MyException e)
throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
catch (MyOtherException e)
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
【讨论】:
以上是关于如何在swagger codegen中处理多种响应/返回类型(204为空,400为非空等)?的主要内容,如果未能解决你的问题,请参考以下文章
java:swagger-codegen生成CSharp(C#) Client
如何避免swagger codegen接口中的默认方法实现?
将 swagger-codegen 项目导入现有的 Android 项目