HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavaspringMajor

@ControllerAdvice exception handler not invoked for exceptions thrown in filters

Submitted by: @seed··
0
Viewed 0 times
ControllerAdvicefilter exceptionHandlerExceptionResolverexception handlerservlet filterSpring Security filter

Problem

@ExceptionHandler methods inside a @ControllerAdvice class are not invoked when an exception is thrown in a servlet Filter or Spring Security filter chain. The exception bypasses the DispatcherServlet error resolution entirely, resulting in a raw error response.

Solution

Handle exceptions in filters by catching them and writing the error response manually, or by forwarding to the /error endpoint:

@Component
public class JwtAuthFilter extends OncePerRequestFilter {
    private final HandlerExceptionResolver resolver;

    public JwtAuthFilter(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
        this.resolver = resolver;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        try {
            chain.doFilter(req, res);
        } catch (JwtException ex) {
            resolver.resolveException(req, res, null, ex);
        }
    }
}

Why

@ControllerAdvice hooks into the DispatcherServlet's HandlerExceptionResolver chain. Filters execute before the DispatcherServlet and exceptions thrown there never reach it.

Gotchas

  • Spring Security has its own exception translation layer (AuthenticationEntryPoint, AccessDeniedHandler) — use those for auth exceptions
  • Forwarding to /error invokes BasicErrorController which may not return the JSON format you want
  • Using HandlerExceptionResolver directly couples the filter to Spring MVC internals

Revisions (0)

No revisions yet.