0

I have a component that implements the HandlerInterceptor interface, and implements the preHandle method. In this method I retrieve a parameter from the request, and throw an IllegalArgumentException if that parameter is missing.

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String parameter = request.getHeader("parameter123");
        if (StringUtils.isEmpty(parameter)) {
            throw new IllegalArgumentException("parameter123 not specified");
        }
        [...]
        return true;
    }

In another class annotated with @ControllerAdvice, I have a ExceptionHandler that catches the IllegalArgumentExceptions and turns those into a formatted response with HTTP status code 400.

When this is executed by triggering a valid path of my API, everything works just fine. Problems arise when I try to call an invalid/unexisting path of my API. The HandlerInterceptor is called and the exception is thrown but my ExceptionHandler is not triggered and the result is a basic HTTP status code 500 exception. It seems to both override the basic HTTP status 404 mechanism, while also preventing the triggering of my ExceptionHandlers (even an ExceptionHandler on Exception.class doesn't ever get called).

Any explanations regarding this behaviour are welcome ! Thanks

  • Hmm, I did some test and it seems like you are right. I was conviced that it works like I explained. Need to investigate this further – Nemanja Jun 07 '22 at 19:32

1 Answers1

1

Although this may be an old question, I want to provide an answer for anyone who may come across it in the future.

When you raise an exception in the preHandle method of a HandlerInterceptor, it may be wrapped in another exception called NestedServletException. This is a specific exception thrown by the Spring framework.

It's worth noting that NestedServletException is a runtime exception that occurs when a servlet or filter throws an exception. It encloses the original exception and provides additional information about the location where the exception occurred.

Francisco
  • 21
  • 1
  • 4
  • Thank you for the input. It doesn't exactly answer why no handler is called though, even when I specify one for Exception.class (which should catch a NestedServletException or RuntimeException for that matter) – Christophe Schutz Jan 24 '23 at 12:56
  • I think you need to add a filter or interceptor to do that: https://stackoverflow.com/questions/34595605/how-to-manage-exceptions-thrown-in-filters-in-spring – Francisco Jan 25 '23 at 17:31