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