0

I have a REST api spring boot application and would like to handle any error in ControllerAdvice, because I would like to have a customised response format and not use the Spring default response.

For example Exception like RequestRejectedException are not handled via Controller advice. Is there an elegant way to handle any possible error in a one handler on Spring?

For the RequestRejectedException I have implemented a GenericFilterBean and reformatted the response there but would like to have a more unified way to handling all errors.

simonC
  • 4,101
  • 10
  • 50
  • 78

2 Answers2

1

Controller Advice is able to handle any exception that gets originated by any flow that starts by controller method invocation.

This is a "Spring MVC"'s generic way to handle exceptions.

Now Spring MVC's infrastructure is technically based on a single servlet (called DispatcherServlet) that can "assign" the controller method to the call by url, http method etc.

However its possible that you use Servlet's filters which are deployed and handled directly by the underlying web container (like tomcat or jetty). So if that code originates the exception, its kind of "out of sight" for spring MVC, it doesn't even reach the MVC controller, so controller advice cannot intercept the exception.

You haven't specified which code exactly originates the RequestRejectedException but it might be possible that this is done outside the spring mvc, hence the controller advice is not applicable...

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

With ControllerAdvice something like :

@ControllerAdvice
class GenericExceptionHandling extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = RuntimeException.class)
    protected ResponseEntity<Object> handleConflict(
      RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }

}

should make sense but since this exception is thrown differently by spring it seems it cannot be handled like that. Read related . So one of the way to handle this is to have a filter with highest order and in that filter catch this exception and convert the response to what you want it to be.

Related stackoverflow thread : Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39