Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

An exception thrown in a servlet filter returns an HTML or default JSON error instead of your @ControllerAdvice format. Why, and how do you make it consistent?

@ControllerAdvice only handles exceptions thrown while DispatcherServlet runs a handler, and a servlet filter runs before DispatcherServlet. An exception from the filter goes to the servlet container, which forwards to /error, where Spring Boot renders its own HTML page or default JSON. To make it consistent we either catch the exception in the filter and write the standard body, or delegate it to Spring's HandlerExceptionResolver so our advice runs, or make /error produce the same format through ErrorAttributes or a custom error controller. Spring Security errors are handled separately by its AuthenticationEntryPoint for 401 and AccessDeniedHandler for 403.

Why this question is asked

A service usually has a polished error format for everything its controllers throw. Then someone adds a filter that checks a tenant header or an API key, and its errors come back as a Whitelabel HTML page in the browser, or as a JSON body with timestamp and path instead of the ProblemDetail fields. Clients that parse errors break on exactly these requests. Interviewers ask this scenario because it shows whether we know where Spring MVC's error handling begins and ends. In this answer, we will recap the request path, reproduce the problem, see why the advice is skipped, and then go through three ways to make errors consistent, plus Spring Security's own handlers.

1A Quick Recap of the Request Path

A request to a Spring Boot web application passes through several layers. The servlet container, such as Tomcat, receives it. It runs the filter chain: servlet filters, objects that can inspect or reject a request before any controller sees it, including Spring Security's filter chain. Only at the end of the chain does DispatcherServlet, Spring MVC's front controller, receive the request and call a controller.

The error handling we configure with @ExceptionHandler and @ControllerAdvice lives inside DispatcherServlet. It is the HandlerExceptionResolver chain that DispatcherServlet calls when a handler throws. Anything that happens before DispatcherServlet is outside its reach.

Step throughWhere a request passes, and where errors are handled
  1. Servlet container (Tomcat)unhandled exceptions -> error page -> /error
  2. Spring Security filter chainAuthenticationEntryPoint (401), AccessDeniedHandler (403)
  3. Our TenantFilterthrows InvalidTenantException: no advice here
  4. DispatcherServletHandlerExceptionResolvers, @ControllerAdvice
  5. Controllerexceptions handled by the advice

5 layers, from the top down. Step through them one at a time.

Our advice only covers the bottom two layers.

2Reproducing the Problem

Here is a filter that rejects requests without a valid tenant header.

Java
@Component
class TenantFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String tenant = req.getHeader("X-Tenant");
if (tenant == null || !tenants.exists(tenant)) {
throw new InvalidTenantException(tenant); // our advice maps this to 400 ... in controllers
}
chain.doFilter(req, res);
}
}
// curl /orders -H "Accept: application/json"
// 500 {"timestamp": "...", "status": 500, "error": "Internal Server Error", "path": "/orders"}
// browser: Whitelabel Error Page

We have an @ExceptionHandler for InvalidTenantException that returns a 400 ProblemDetail, yet the client gets a 500 in Spring Boot's default shape.

3Why the Advice Never Sees It

The exception is thrown inside the filter, before chain.doFilter reaches DispatcherServlet. No resolver chain is involved, so it travels up through the other filters to the container. The container treats an unhandled exception as status 500 and looks for an error page. Spring Boot registers a global error page at /error, so the container makes an internal error dispatch to that path, where BasicErrorController builds the response from ErrorAttributes: an HTML page for browsers, a JSON map of timestamp, status, error and path for everyone else.

So the format is not wrong by accident. It is the correct output of a different error handling system, the one for errors that never reached Spring MVC.

4Fix 1: Handle the Error in the Filter

The most direct fix is that the filter does not throw at all. It writes the response itself, in the standard format, and stops the chain. If the service has a shared helper that writes a ProblemDetail, the filter uses it so the body is identical to the advice's.

Java
if (tenant == null || !tenants.exists(tenant)) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Unknown or missing tenant");
pd.setProperty("code", "invalid_tenant");
res.setStatus(400);
res.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE);
objectMapper.writeValue(res.getOutputStream(), pd);
return; // do not call chain.doFilter
}
// 400 {"type": "about:blank", "title": "Bad Request", "status": 400, "detail": "Unknown or missing tenant", "code": "invalid_tenant"}

This works well for a few expected rejections. Its weakness is duplication: the mapping from exception to response now exists both in the advice and in the filter.

5Fix 2: Delegate to HandlerExceptionResolver

Spring MVC registers its resolver chain as a bean named handlerExceptionResolver. A filter can inject it and pass the exception to it, so our @ControllerAdvice produces the response exactly as it does for controllers.

Java
@Component
class TenantFilter extends OncePerRequestFilter {
private final HandlerExceptionResolver resolver;
TenantFilter(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
this.resolver = resolver;
}
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
try {
checkTenant(req); // throws InvalidTenantException
} catch (InvalidTenantException ex) {
resolver.resolveException(req, res, null, ex); // our advice writes the 400 ProblemDetail
return;
}
chain.doFilter(req, res); // outside the try: downstream errors are not swallowed
}
}

Notice two details. The qualifier is needed because Spring Boot's DefaultErrorAttributes is also a HandlerExceptionResolver bean. And the handler argument is null, because no controller was chosen yet, so an advice limited with basePackages or assignableTypes will not apply; the advice that should handle filter errors must be unrestricted.

6Fix 3: Make /error Produce the Same Format

The safety net covers everything that still reaches the container, including exceptions from third-party filters we cannot change. We can customise ErrorAttributes, by extending DefaultErrorAttributes and returning the same keys as our ProblemDetail, or replace the error controller with our own implementation of ErrorController mapped to /error that returns a ProblemDetail built from the stored status and exception. With either in place, even an unexpected failure outside Spring MVC has the standard shape.

Spring Security is a special case. Its ExceptionTranslationFilter catches AuthenticationException and AccessDeniedException from the security chain and calls an AuthenticationEntryPoint for 401 and an AccessDeniedHandler for 403. Their default responses are not our format, so we configure both, for example with http.exceptionHandling(e -> e.authenticationEntryPoint(...).accessDeniedHandler(...)), and implement them by writing the standard ProblemDetail or by delegating to the handlerExceptionResolver as in Fix 2.

7Follow-up questions

Why not wrap the whole chain.doFilter call in a try-catch?

Because then the filter catches every exception from everything downstream, including controllers, and it would bypass the advice's precise handling or handle errors twice. A filter should catch only the exceptions from its own logic and let the rest flow through their normal path.

Can a @PreAuthorize failure end up in my catch-all advice?

Yes. Method security on a controller throws AccessDeniedException inside DispatcherServlet, so the advice sees it first. If the advice has a catch-all for Exception, it turns the 403 into a 500. The advice should rethrow AccessDeniedException and AuthenticationException, or handle them explicitly, so Spring Security's handlers keep working.

How do we test that every error source uses the same format?

With an integration test, for example @SpringBootTest with a real filter chain through MockMvc or a random port, that triggers each source: a controller exception, the tenant filter, a missing token, a forbidden call and an unmapped URL. Each test asserts the content type application/problem+json and the shared fields.

8Conclusion

In this answer, we saw that @ControllerAdvice only covers exceptions raised while DispatcherServlet handles a request, so a filter's exception travels to the container and is rendered by Spring Boot's /error page. We made the format consistent by writing the standard body in the filter, by delegating to the handlerExceptionResolver bean so the advice runs, and by customising ErrorAttributes or the error controller as a safety net. Spring Security's 401 and 403 responses come from its AuthenticationEntryPoint and AccessDeniedHandler, which we configure to write the same format.

What to say in the interviewAbout 80 seconds aloud

Open with

The reason is where the exception happens. @ControllerAdvice is part of DispatcherServlet's HandlerExceptionResolver chain, so it only sees exceptions thrown while a handler runs. A servlet filter runs before DispatcherServlet, so its exception goes up to the container, which treats it as a 500 and forwards to /error.

Then, if they want more

Boot's BasicErrorController renders that with ErrorAttributes: the Whitelabel HTML page for browsers or the default JSON with timestamp, status, error and path. To fix it I have three options, and I often use more than one. In the filter, I can avoid throwing and write the standard ProblemDetail myself, which is fine for one or two expected rejections.

Better, I inject the bean named handlerExceptionResolver, with a qualifier because Boot's error attributes is also a resolver, and call resolveException with a null handler, so my advice writes the response; that advice must not be restricted by package.

As a safety net, I customise ErrorAttributes or provide my own ErrorController for /error so anything else that escapes still has the same shape. Security is separate: its ExceptionTranslationFilter calls the AuthenticationEntryPoint for 401 and the AccessDeniedHandler for 403, so I configure both to write ProblemDetail. Then an integration test triggers each source and checks the format.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An exception thrown in a servlet filter returns an HTML or default JSON error instead of...": https://scrivio-interview-library.netlify.app/spring-boot/error-handling/e1608a1c4f/