Sub topic 8
One place for all handlers: @RestControllerAdvice
This chapter assumes you can write a Spring Boot REST controller, know the difference between checked and unchecked exceptions, and have seen a local @ExceptionHandler method. Here you move those handlers into one class that covers every controller.
Why a global handler
A local @ExceptionHandler only applies to the controller that declares it. If OrderController and CustomerController both throw "not found" errors, you would copy the same handler into each one. The bodies drift apart, and clients receive different error shapes from the same API.
@RestControllerAdvice fixes this. It marks a class whose @ExceptionHandler methods apply to all controllers. It combines @ControllerAdvice with @ResponseBody, so each return value is written to the response body as JSON.
The domain exception
The handler needs something to catch. This exception carries the missing order's id, so the handler can build a response without parsing the message.
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;
}
}A global handler
The class below handles three cases: the domain exception, validation failures, and everything else.
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;
}
}Three details matter here.
- The domain handler returns a
ProblemDetaildirectly. Spring sets the HTTP status from theProblemDetailitself, so you do not need@ResponseStatus. - Extending
ResponseEntityExceptionHandlergives you ready-made handling for Spring MVC's own exceptions, such as unsupported media types or malformed JSON. The validation method overrides one of its hooks, so the 400 response uses the same body shape as your other errors. - The catch-all logs the full stack trace on the server and returns a fixed message. The client never sees the exception text.
How Spring picks a handler
When a controller throws, Spring looks for the most specific matching @ExceptionHandler. A handler for OrderNotFoundException wins over one for Exception. A local handler in the controller wins over one in an advice class.
Limiting the scope
By default an advice class applies to every controller. You can narrow it with attributes on the annotation:
@RestControllerAdvice(basePackages = "com.example.orders")
class OrdersOnlyAdvice {
}You can also use annotations or assignableTypes. Use scoping when two parts of an application need different error contracts. If you have several advice classes, add @Order to control which is consulted first.
Common errors
- The handler never runs. The class is outside the component-scan packages, or the exception is thrown from a filter. Filters run before the dispatcher servlet, so advice classes do not see their exceptions.
- The response is a plain string instead of JSON. You used
@ControllerAdvicewithout@ResponseBody. Use@RestControllerAdvice. - A generic handler hides a specific one. Specificity decides the match, not declaration order. Check that the specific exception is not wrapped in another exception type.
Exercise
Two controllers throw OrderNotFoundException. You declare a handler for it in one controller and another in an @RestControllerAdvice class. A request to the second controller throws the exception. Which handler runs, and what happens when the first controller throws it?
Show answer
For the second controller, the advice handler runs, because it has no local handler. For the first controller, the local handler runs, because a local @ExceptionHandler takes priority over advice handlers.
Exercise
Why does the ApiExceptionHandler extend ResponseEntityExceptionHandler instead of only declaring @ExceptionHandler(Exception.class)?
Show answer
The base class already handles Spring MVC's own exceptions with the correct status codes. A bare catch-all handler would map them all to 500, and the base class also provides hooks such as handleMethodArgumentNotValid for a consistent body.