2

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

1 Answer 1

-1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.