Sub topic 5
How Spring MVC turns an exception into a response
This chapter assumes you can write a Spring Boot REST controller, you know that unchecked exceptions propagate out of controller methods, and you have seen the default /error response from the earlier chapter. Here you will follow an exception from the controller to the bytes sent to the client. Knowing that path explains why @ExceptionHandler methods sometimes seem to be ignored, and why some errors still return Boot's default error JSON.
The central idea: a chain of resolvers
When a controller method throws, the exception reaches DispatcherServlet, the front controller that dispatches every Spring MVC request. The servlet does not turn the exception into a response itself. It asks each registered HandlerExceptionResolver in order whether it can handle the exception. This is the chain of responsibility pattern.
A resolver has three possible outcomes:
- It returns
null, which means "not mine". The servlet asks the next resolver. - It returns a
ModelAndView, which means "handled". The chain stops. An emptyModelAndViewmeans the resolver wrote the response itself, as@ExceptionHandlermethods in a REST API do. - It throws an exception. This is rare and usually signals a bug in the handler.
If every resolver returns null, DispatcherServlet rethrows the original exception to the servlet container. The container then reports a 500 and performs an error dispatch to /error, where Boot's BasicErrorController builds the default body.
The resolvers in a Boot application
A Spring Boot web application normally has these resolvers, in this order:
| Order | Resolver | What it handles |
|---|---|---|
| Highest precedence | `DefaultErrorAttributes` | Records the exception as a request attribute for `/error`. Always returns `null`. |
| 0 | `ExceptionHandlerExceptionResolver` | Methods annotated with `@ExceptionHandler`, local or in `@ControllerAdvice`. |
| 1 | `ResponseStatusExceptionResolver` | `@ResponseStatus` on an exception class, and `ResponseStatusException`. |
| 2 | `DefaultHandlerExceptionResolver` | Spring's own exceptions, such as a wrong HTTP method (405) or a missing parameter (400). |
The last three are wrapped in one HandlerExceptionResolverComposite bean. DefaultErrorAttributes is a separate bean that implements the same interface. It never handles anything. It exists so that /error can later report the original exception.
You can check this in your own application. This component prints the resolvers at startup:
package com.example.orders;
import java.util.List;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite;
@Component
class ResolverChainPrinter implements ApplicationRunner {
private final List<HandlerExceptionResolver> resolvers;
ResolverChainPrinter(List<HandlerExceptionResolver> resolvers) {
this.resolvers = resolvers;
}
@Override
public void run(ApplicationArguments args) {
for (HandlerExceptionResolver resolver : resolvers) {
System.out.println(resolver.getClass().getSimpleName());
if (resolver instanceof HandlerExceptionResolverComposite composite) {
for (HandlerExceptionResolver inner : composite.getExceptionResolvers()) {
System.out.println(" " + inner.getClass().getSimpleName());
}
}
}
}
}A typical output is:
DefaultErrorAttributes
HandlerExceptionResolverComposite
ExceptionHandlerExceptionResolver
ResponseStatusExceptionResolver
DefaultHandlerExceptionResolverThe exact list can differ with your Boot version and configuration. The relative order of the three inner resolvers is what matters.
The full path
The diagram shows the decision points for an exception thrown in a controller.
Two details in this diagram surprise many developers.
First, ResponseStatusExceptionResolver and DefaultHandlerExceptionResolver do not write a body. They call HttpServletResponse.sendError(status, reason). That marks the response as an error, and the container dispatches to /error. The body you receive for a @ResponseStatus exception is therefore Boot's default error JSON, shaped by the server.error.* properties.
Second, an @ExceptionHandler method is the only mechanism in this chain that gives you full control of the body without going through /error. That is why the later chapters build the error contract on it.
How the `@ExceptionHandler` search works
ExceptionHandlerExceptionResolver searches in a fixed order, and the first match wins:
@ExceptionHandlermethods in the controller class that threw the exception, including its superclasses.@ExceptionHandlermethods in@ControllerAdviceand@RestControllerAdvicebeans, in order of@OrderorOrdered. A lower value is consulted first. An advice bean without an order is consulted last.
Inside one class, Spring picks the handler whose declared exception type is closest to the thrown type in the class hierarchy. If two methods in the same class are equally close, Spring throws an IllegalStateException about an ambiguous mapping when it handles the exception.
Spring also matches the exception's causes. If no handler matches the thrown exception, Spring tries its cause chain. This means a handler for SQLException can catch a wrapper such as DataAccessException that has a SQLException as its cause.
The consequence of step 1 before step 2 is important. A local handler beats a global one even when the global one is more specific. The following scratch example shows it:
package com.example.orders;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestController
class PrecedenceDemoController {
@GetMapping("/demo/state")
String state() {
throw new IllegalStateException("boom");
}
@ExceptionHandler(RuntimeException.class)
ResponseEntity<String> local(RuntimeException ex) {
return ResponseEntity.status(409).body("local: " + ex.getMessage());
}
}
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
class PrecedenceDemoAdvice {
@ExceptionHandler(IllegalStateException.class)
ResponseEntity<String> advice(IllegalStateException ex) {
return ResponseEntity.status(422).body("advice: " + ex.getMessage());
}
}A GET /demo/state request returns 409 with the body local: boom. The advice handler matches the exception type more closely, but Spring never reaches it because the controller already has a matching method. Remove the local method and the same request returns 422.
What the chain does not cover
The resolver chain starts inside DispatcherServlet. These failures happen outside it:
- Exceptions thrown in servlet filters, including Spring Security filters, never reach
@ExceptionHandlermethods. The container handles them and dispatches to/error. Spring Security has its own entry point and access-denied handler for these cases. - Exceptions after the response is committed. If the controller has already flushed part of the body, no resolver can change the status line. Streaming responses are the usual cause.
- Exceptions raised while rendering a view or serializing a body can be handled only if the response has not been committed yet. A
HttpMessageNotWritableExceptionis an example. - Errors that are not exceptions, such as
OutOfMemoryErrorraised as anError. A handler forExceptiondoes not catch them. Do not try to handle them in a controller advice.
A common symptom: your advice returns clean JSON for most errors, but a request rejected by a security filter returns Boot's default body. This is expected, because that request never reached the chain.
Where `/error` still matters
Even with a complete global handler, the /error path is still used. It handles:
- errors from
sendError, such as@ResponseStatusexceptions and Spring's own 4xx errors, unless you enabled ProblemDetail support or extendResponseEntityExceptionHandler - 404 responses for URLs with no mapping, in versions where this is not raised as an exception
- failures in filters
- any exception no handler claimed
This is why a robust design does two things. It handles the exceptions you care about in one advice, with a catch-all Exception handler as the last resort. It also configures server.error.* so the fallback does not leak details. The following chapters build both.
Debugging an exception that is not handled
When a handler does not fire, work through these checks in order:
- Is the exception thrown inside a controller, or earlier in a filter? Filters bypass the chain.
- Is the advice class a Spring bean? It needs
@RestControllerAdviceand must be inside the component scan. - Does a controller-local
@ExceptionHandlertake precedence? - Is another advice with a lower order value matching first?
- Is the thrown exception wrapped? Log
ex.getClass()andex.getCause(). Spring checks causes, but your handler's type must match one of them. - Is the response committed? Look for a log line like "Response already committed".
You can turn on resolver logging to see decisions. Set logging.level.org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver=DEBUG to log which handler resolved an exception. Spring logs resolved exceptions from AbstractHandlerExceptionResolver at warn level by default, which is useful when a DefaultHandlerExceptionResolver quietly produces a 400.
Writing your own resolver
You rarely need a custom HandlerExceptionResolver. Prefer @ExceptionHandler, which is easier to read and to test. A custom resolver makes sense only for cross-cutting behavior that must work for every handler type, such as adding a header to all failures. It is registered as a bean and implements one method, resolveException. Return null to defer to the rest of the chain.
Exercise
A controller method throws a custom exception annotated with @ResponseStatus(HttpStatus.NOT_FOUND). Your @RestControllerAdvice also contains an @ExceptionHandler(Exception.class) method. Which one produces the response, and why?
Show answer
The advice's @ExceptionHandler(Exception.class) method does. ExceptionHandlerExceptionResolver has order 0 and runs before ResponseStatusExceptionResolver, which has order 1. Because the handler for Exception matches every exception, the chain stops there and the @ResponseStatus annotation is never consulted. To keep the 404, add a more specific handler for that exception, or remove the catch-all.
Exercise
An @ExceptionHandler in your advice returns clean ProblemDetail JSON for a missing order, but a request with an invalid JWT returns Boot's default error JSON. What explains the difference?
Show answer
Spring Security rejects the request in a servlet filter, before DispatcherServlet runs. The resolver chain is never involved, so the advice cannot see the exception. The container handles it and dispatches to /error, which builds the default body. To change that response, configure Spring Security's authentication entry point and access-denied handler.