swagger代码生成器如何处理多种响应/返回类型(204为空,400为非空等)?

时间:2020-02-20 17:07:15

标签: java swagger openapi swagger-codegen

我正在使用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 个答案:

答案 0 :(得分: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());
        }
}