How to rethrown an exception in Java

135 Views Asked by At

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.

1

There are 1 best solutions below

3
Elikill58 On

You can add the ApiException in throws declaration like that :

public ResponseEntity<MyResponse> LoginMethod(//some parameters...) throws ApiException {
   // here your code that can create teh ApiException
}

Now the method which call this will ask for the throw exception too. You will be able to manage exception in it.

You can also create a new object which contains all informations that you need. It will also format informations to be always the same, not depending of the throwed error.