1

My basic need was to catch user defined exceptions and return generic responses. For this I used the @ControllerAdvice with @ExceptionHandler. See example below

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler  {

    @ExceptionHandler(PersonNotFoundException.class)
    public void handleBadPostalCode(HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value(), "Invalid person Id");
    }

    @ExceptionHandler(Exception.class)
    public void handleDefault(Exception e, HttpServletResponse response) throws IOException {
        e.printStackTrace();
        response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Unknown error happened");
    }
}

The PersonNotFoundException is handled as expected. But other exceptions default handlers are gone and only Http code without body is returned. Apparently this is the expected behaviour when extending ResponseEntityExceptionHandler. I can override other default exceptions but this is not ideal. Using a generic Exception.class handler will force me to return one HTTP Code for all of them.

SO i'm looking for a way to handle my own exceptions globally in the ControllerAdvice or similar without having to override default exception handlers

Thanks

Wildfire
  • 162
  • 2
  • 16

1 Answers1

0

The quickest and the most cleaner way to handle it is just using @ResponseStatus on your exception class:

 @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")  // 404
 public class OrderNotFoundException extends RuntimeException {
     // ...
 }

Also is extending ResponseEntityExceptionHandler necessary? IMO it's not. You can handle it only by using @ControllerAdvice (or @RestControllerAdvice) and @ExceptionHandler

More over you can directly return your response in method without injecting HttpServletResponse and calling send() method. Take a look into this guide.

Kamil W
  • 2,230
  • 2
  • 21
  • 43