Sub topic 7
Handling exceptions inside a controller with @ExceptionHandler
This chapter assumes you can write a Spring Boot REST controller and that you know what ProblemDetail is. It also assumes you have a custom exception such as OrderNotFoundException, which carries the missing order id.
What @ExceptionHandler does
@ExceptionHandler marks a method as the handler for one or more exception types. When a request-mapped method in the same controller throws a matching exception, Spring calls your handler. It uses the handler's return value to build the response, so the exception never reaches the default /error page.
A handler declared in a controller applies only to that controller. Exceptions thrown by other controllers ignore it. Sharing handlers across controllers is the job of @RestControllerAdvice, covered in the next chapter.
A local handler
package com.example.orders;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/shipments")
class ShipmentController {
private final Map<Long, String> shipments = Map.of(1L, "Packed");
@GetMapping("/{id}")
String status(@PathVariable long id) {
String status = shipments.get(id);
if (status == null) {
throw new OrderNotFoundException(id);
}
return status;
}
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail handleNotFound(OrderNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Shipment not found");
problem.setProperty("orderId", ex.getOrderId());
return problem;
}
}A request to /shipments/7 now returns a 404 with a JSON body that contains title, detail, status and orderId. The ProblemDetail carries its own status, so you don't need @ResponseStatus on the handler.
How Spring picks a handler
Local handlers take precedence over advice handlers. Within one class, Spring picks the handler whose declared exception type is closest to the thrown exception in the class hierarchy.
Handler signatures
A handler method can accept several argument types:
- The exception itself, typed as narrowly as you need.
HttpServletRequestorWebRequest, for the request path or headers.Locale,Principaland similar request-scoped values.
Common return types:
| Return type | Effect |
|---|---|
| `ProblemDetail` | Body and status come from the object. |
| `ResponseEntity<T>` | You control status, headers and body. |
| Any object | Serialized as the body. Status is 200 unless you add `@ResponseStatus`. |
One handler can cover several exception types:
@ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class})
ProblemDetail handleBadState(RuntimeException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
}The parameter type must be a common supertype of everything you list.
Common errors
- Status 200 with an error body. A handler returning a plain object without
@ResponseStatusproduces a 200. ReturnProblemDetailorResponseEntity, or add the annotation. - Ambiguous handlers. Two methods in one class that handle the same exception type make Spring throw an
IllegalStateExceptionwhen the exception occurs. Keep one handler per type. - Handlers that throw. An exception thrown inside the handler is not handled by a sibling handler. Keep handler code simple.
- Wrong scope. If the same exception is thrown by two controllers, a local handler fixes only one of them.
Exercise
A controller has a local @ExceptionHandler for OrderNotFoundException, and a @RestControllerAdvice also handles OrderNotFoundException. The controller throws it. Which handler runs, and why does a plain-object handler return 200 unless you act?
Show answer
The local handler in the controller runs, because Spring checks the controller's own handlers before any advice. A plain-object return value is just serialized as the body, so the status stays 200 unless you add @ResponseStatus, return a ResponseEntity, or return a ProblemDetail that carries its own status.