I am using maven codegen plugin to generate the controller interface with a schema like the following
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/MyResponse'
description: OK
'401':
content:
application/json:
schema:
$ref: '#/components/schemas/MyError'
The interface like the following
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Authentication succeeded", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MyResponse.class))),
@ApiResponse(responseCode = "401", description = "Authentication failed", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MyError.class))) })
@RequestMapping(value = "/login", method = RequestMethod.POST)
default ResponseEntity<MyResponse> LoginMethod(//some parameters...) { //something}
In my controller, I would like to call an external API which throws an API exception
public ResponseEntity<MyResponse> LoginMethod(//some parameters...) {
try {
//call external API which throw an exception
} catch(ApiException e){
e.getResponseBody; // This is a string type of MyError class in JSON format returned
// throw e;
}
I would like to redirect the response body but the interface defines the return type to be ResponseEntity so I can't simply rethrow the exception or return ResponseEntity.
@ApiResponse seems not correcting the response type as well.
As stated in this question, How to handle multiple response/return types (empty for 204, non-empty for 400 etc) in swagger codegen?
I can throw as this way
throw new ResponseStatusException(HttpStatus.valueOf(e.getCode()), e.getResponseBody());
But is there a better way to do that? I just want to return the e.getResponseBody() as an object instead of a string.
Many thanks.