Video in progress
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:
- 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())); } - Delegate to
HandlerExceptionResolver. Inject thehandlerExceptionResolverbean into the filter and callresolver.resolveException(req, res, null, e). That way the logic in your advice gets reused. - Spring Security errors have their own place:
AuthenticationEntryPoint(401) andAccessDeniedHandler(403). You provide them throughhttp.exceptionHandling(...).
If the check really belongs to the controller, move it from a Filter to a HandlerInterceptor: interceptor exceptions do reach the advice.
Sign up to mark studied questions and save your progress.