Warm tip: This article is reproduced from stackoverflow.com, please click
java openapi swagger swagger-codegen

How to handle multiple response/return types (empty for 204, non-empty for 400 etc) in swagger codeg

发布于 2020-05-10 18:37:09

I'm using openapi version 3.0.2.

I have the following spec which describes my responses:

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.

For most response codes, I do not return any response body, but for the 400 response code, I want to return the Error object:

Error:
    type: object
    properties:
        code:
            type: string
        message:
            type: string
    required:
        - code
        - message

When I generate the Java server code for this endpoint, the return type for the method is a ResponseEntity<Void>, meaning I can't return the Error object?

It seems similar to these issues:

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

I don't know if this is something that has been fixed yet, or if there is any workaround for this?

Questioner
Rory
Viewed
10
Rory 2020-02-25 18:49

I used the following approach described here to resolve this:

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