温馨提示:本文翻译自stackoverflow.com,查看原文请点击:java - How to handle multiple response/return types (empty for 204, non-empty for 400 etc) in swagger codeg
java openapi swagger swagger-codegen

java - Swagger Codeg如何处理多种响应/返回类型(204为空,400为非空等)

发布于 2020-05-14 00:44:05

我正在使用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

我不知道这是否已解决,或者是否有任何解决方法?

查看更多

提问者
Rory
被浏览
2
Rory 2020-02-25 18:49

我使用此处描述的以下方法来解决此问题:

@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());
        }
}