Video in progress

Strong Middle 🌱 Spring

Why doesn't an exception thrown inside a Filter reach @RestControllerAdvice, and how do you turn it into a clean response?

@ControllerAdvice runs inside the DispatcherServlet, while a Servlet Filter runs before it. An error in a filter goes straight out to the container, and Boot's /error page answers.

📖 Answer

The request path: Tomcat → Filters (Spring Security lives here too) → DispatcherServlet → interceptor → controller. @RestControllerAdvice is invoked by ExceptionHandlerExceptionResolver, which sits inside DispatcherServlet. The filter is outside it, so its exception bypasses the advice.

In practice the client gets Boot's default /error response: a different format, and sometimes a 403 instead of a 500 (because /error also goes through security).

Solutions:

  1. Let the filter write the response itself. This is enough for simple cases:
    try {
        chain.doFilter(req, res);
    } catch (TenantNotFoundException e) {
        res.setStatus(400);
        res.setContentType("application/problem+json");
        objectMapper.writeValue(res.getOutputStream(),
            ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, e.getMessage()));
    }
    
  2. Delegate to HandlerExceptionResolver. Inject the handlerExceptionResolver bean into the filter and call resolver.resolveException(req, res, null, e). That way the logic in your advice gets reused.
  3. Spring Security errors have their own place: AuthenticationEntryPoint (401) and AccessDeniedHandler (403). You provide them through http.exceptionHandling(...).

If the check really belongs to the controller, move it from a Filter to a HandlerInterceptor: interceptor exceptions do reach the advice.