Sub topic 8
One place for all handlers: @RestControllerAdvice
This chapter assumes you can write a Spring Boot REST controller and throw a custom exception from it. It also assumes you know what an @ExceptionHandler method is. You should know basic HTTP status codes. The code uses Spring Boot 3 (Spring Framework 6) and the jakarta.* packages.
The problem with local handlers
An @ExceptionHandler method inside a controller only handles exceptions thrown by that controller. If OrderController and CustomerController both throw OrderNotFoundException, each needs its own copy of the handler. The copies drift apart over time. One returns a plain string, another returns JSON, and a third forgets to log.
@RestControllerAdvice fixes this. It marks a class whose @ExceptionHandler methods apply to every controller in the application, or to a subset you choose. The result is one place that defines your API's error contract.
@RestControllerAdvice is shorthand for @ControllerAdvice plus @ResponseBody. Return values are written to the response body, as with @RestController. They are not treated as view names.
A minimal advice class
Start with the custom exception from the previous chapters:
package com.example.orders;
public class OrderNotFoundException extends RuntimeException {
private final long orderId;
public OrderNotFoundException(long orderId) {
super("Order " + orderId + " was not found");
this.orderId = orderId;
}
public long getOrderId() {
return orderId;
}
}Here is the smallest useful advice. It maps that exception to a 404 and returns a ProblemDetail, the RFC 9457 body type covered in the next chapter:
package com.example.orders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
public ProblemDetail handleOrderNotFound(OrderNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
problem.setProperty("orderId", ex.getOrderId());
return problem;
}
}Spring Boot finds this class through component scanning, like any other @Component. You don't register it anywhere. The handler method does not need @ResponseStatus. When a handler returns a ProblemDetail, Spring uses its status field as the HTTP status.
Handler methods accept the same kinds of parameters as controller methods. The exception is always available. You can also declare HttpServletRequest, WebRequest, Locale, Principal, and similar types.
How Spring picks a handler
When a controller throws, Spring MVC asks a chain of exception resolvers to handle it. The ExceptionHandlerExceptionResolver is the one that runs @ExceptionHandler methods. It searches in this order:
@ExceptionHandlermethods in the controller that threw.- Methods in each
@ControllerAdviceor@RestControllerAdvicebean, ordered by@Order(orOrdered). Beans without an order come last.
Inside one class, the handler whose declared exception type is closest to the thrown type wins. A handler for OrderNotFoundException beats one for RuntimeException, which beats one for Exception.
The first advice bean that has any matching method handles the exception. Spring does not compare matches across advice beans. A broad @ExceptionHandler(Exception.class) in a high-priority advice therefore beats a specific handler in a lower-priority advice.
If two methods in the same class declare the same exception type, Spring fails with an "Ambiguous @ExceptionHandler method mapped" error. It reports this when the second handler is first needed, not at startup.
Limiting which controllers an advice covers
By default an advice applies everywhere. The annotation attributes narrow that.
| Attribute | Selects controllers by | Example |
|---|---|---|
| `basePackages` | Package name | `@RestControllerAdvice(basePackages = "com.example.orders")` |
| `basePackageClasses` | Package of a marker class | `@RestControllerAdvice(basePackageClasses = OrderController.class)` |
| `assignableTypes` | Controller class or supertype | `@RestControllerAdvice(assignableTypes = OrderController.class)` |
| `annotations` | Annotation on the controller | `@RestControllerAdvice(annotations = PublicApi.class)` |
Scoping is useful when one application serves two APIs with different error formats. For example, a public API may use ProblemDetail while an internal API keeps an older format. Give each advice its own scope, and use @Order if the scopes could overlap.
Extending ResponseEntityExceptionHandler
Your own exceptions are only part of the picture. Spring MVC raises its own exceptions for malformed JSON, unsupported media types, missing parameters, and unmatched methods. Left alone, these produce the default Boot error body, which is a different shape from yours.
ResponseEntityExceptionHandler is a base class that already handles these exceptions. It maps each to the right status and, in Spring 6, to a ProblemDetail body. Extend it, and override only the methods you want to change. The next advice does that. It overrides the validation handler, which the next chapter covers in depth, and adds a catch-all:
package com.example.orders;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);
@ExceptionHandler(OrderNotFoundException.class)
public ProblemDetail handleOrderNotFound(OrderNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
problem.setProperty("orderId", ex.getOrderId());
return problem;
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.toList();
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
problem.setTitle("Invalid request");
problem.setProperty("errors", errors);
return ResponseEntity.status(status).headers(headers).body(problem);
}
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex) {
log.error("Unhandled exception", ex);
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
problem.setTitle("Internal server error");
return problem;
}
}The base class declares its own @ExceptionHandler for the long list of Spring MVC exceptions. For those types it is a closer match than Exception.class, so your catch-all does not swallow them. ResponseStatusException also reaches the base class's handling, because in Spring 6 it extends ErrorResponseException.
The catch-all handler gives the client a generic message and keeps the details in the log. Which exception details to hide is covered in a later chapter.
What an advice cannot see
An advice only handles exceptions raised while a controller handler method runs, including argument resolution and validation. Three kinds of failure never reach it:
- Exceptions thrown in servlet filters, including Spring Security filters. A missing or invalid credential gives a 401 or 403 from the security configuration. Those go through Security's own entry point and access-denied handler.
- A request that matches no controller at all. With default settings Spring answers with its own not-found handling, and with
spring.mvc.problemdetails.enabled=truethe body is aProblemDetail. - Errors after the response has started streaming. The status line is already sent, so you cannot change it.
When an exception escapes the advice, the servlet container forwards to /error. There the default Boot handling from the earlier chapter applies.
Practical advice
- Keep a single advice for the whole API when you can. Split it only when scopes truly differ.
- Group handlers by meaning. Put domain exceptions first, then framework exceptions, then the catch-all last. Order inside the file has no effect, but it makes review easier.
- Log in the advice, once per exception. If the controller or service already logs and rethrows, you get duplicate stack traces. Log at
WARNor lower for client errors and atERRORfor the catch-all. - Prefer returning
ProblemDetailorResponseEntity<ProblemDetail>. Mixing return types such asString, maps, and custom DTOs produces an inconsistent contract. - Treat the advice as an API. Test it with
@WebMvcTest, which loads@RestControllerAdvicebeans along with the controller.
Exercise
An application has two advice beans. GlobalAdvice has @Order(2) and handles OrderNotFoundException with a 404. CatchAllAdvice has @Order(1) and handles Exception with a 500. A controller throws OrderNotFoundException. What status does the client get, and how do you fix it?
Show answer
The client gets 500. Spring checks advice beans in order, and the first bean with any matching method handles the exception. CatchAllAdvice runs first, and its Exception handler matches every exception. Spring does not compare the match quality across beans. To fix it, give the catch-all the lowest priority (for example @Order(Ordered.LOWEST_PRECEDENCE)) or move the handlers into one advice class, where the closest exception type wins.