Sub topic 5
How Spring MVC turns an exception into a response
This chapter assumes you can write a Spring Boot REST controller, know the difference between checked and unchecked exceptions, and know common HTTP status codes. It explains what happens between a throw in your controller and the HTTP response the client receives.
The resolver chain
When a controller method throws, DispatcherServlet does not let the exception reach the servlet container. It catches it and asks a list of HandlerExceptionResolver beans to turn it into a response. The resolvers are tried in order, and the first one that handles the exception wins.
With Spring Boot's defaults, the chain contains three resolvers that matter to you:
ExceptionHandlerExceptionResolverruns methods annotated with@ExceptionHandler, both local to the controller and global in@RestControllerAdviceclasses.ResponseStatusExceptionResolverhandles exceptions annotated with@ResponseStatusand instances ofResponseStatusException.DefaultHandlerExceptionResolvermaps Spring MVC's own exceptions, such asHttpRequestMethodNotSupportedException(405) orHttpMessageNotReadableException(400), to status codes.
Why the order matters
Because @ExceptionHandler methods are checked first, a handler you write can override how a @ResponseStatus exception or a Spring MVC exception is reported. This is how a global handler can give every error the same body shape.
Inside ExceptionHandlerExceptionResolver, Spring picks the handler whose declared exception type is closest to the thrown type in the class hierarchy. If you declare handlers for both OrderNotFoundException and Exception, a thrown OrderNotFoundException goes to the first one. Handlers in the controller itself take priority over handlers in @RestControllerAdvice classes.
The fallback to /error
If no resolver handles the exception, DispatcherServlet rethrows it. The servlet container then treats the request as failed and forwards it to the /error path. Spring Boot registers BasicErrorController there, and it builds the default JSON body.
You can see which path a response took by looking at its body. A body with timestamp, status, error and path fields came from /error. A body from your own handler has whatever shape you gave it.
The next example shows a resolver at work. This exception is handled by ResponseStatusExceptionResolver, because it is annotated and no @ExceptionHandler matches it.
package com.example.orders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.CONFLICT)
public class DuplicateOrderException extends RuntimeException {
public DuplicateOrderException(String message) {
super(message);
}
}Common errors
- Expecting a handler to catch everything. Exceptions thrown before a controller is chosen, for example in a servlet filter, never reach
DispatcherServlet's resolvers. They end up at/error. - A catch-all
Exceptionhandler hiding Spring's own mappings. A global@ExceptionHandler(Exception.class)also receives a 405 or 400 exception, because the handler resolver runs first. Unless you handle those types too, clients get a 500 for what is really their mistake. ExtendingResponseEntityExceptionHandleravoids this, because it already handles the standard Spring MVC exceptions. - Catching and swallowing exceptions in the controller. If your own
try/catchreturns normally, the resolver chain never runs. - Assuming the same flow in WebFlux. Reactive applications do not use
HandlerExceptionResolver. A later chapter covers the differences.
Exercise
A controller throws a DuplicateOrderException annotated with @ResponseStatus(HttpStatus.CONFLICT). A @RestControllerAdvice also contains an @ExceptionHandler(RuntimeException.class) method that returns a 500. Which status does the client see, and why?
Show answer
The client sees 500. ExceptionHandlerExceptionResolver runs before ResponseStatusExceptionResolver, and DuplicateOrderException is a RuntimeException, so the handler matches first and the annotation is never consulted. To get a 409, add a more specific @ExceptionHandler(DuplicateOrderException.class) or remove the broad handler.
Exercise
A response body contains timestamp, status, error and path. Which component produced it, and what does that tell you about your handlers?
Show answer
BasicErrorController produced it at /error. No resolver in the chain handled the exception, so none of your @ExceptionHandler methods matched it. It may also have been thrown outside the controller layer, for example in a filter.