Sub topic 7
Handling exceptions inside a controller with @ExceptionHandler
This chapter assumes you can write a Spring Boot REST controller and have a custom exception such as OrderNotFoundException (from the chapter on custom exceptions). You should also know how Spring Boot's default /error response looks. Here you will map exceptions to responses with methods inside the controller itself.
What @ExceptionHandler does
@ExceptionHandler marks a method as the handler for one or more exception types. When a request handler method in the same controller throws a matching exception, Spring skips the default error page and calls your method. Whatever your method returns becomes the response, using the same message converters as a normal controller method.
A handler declared inside a controller is local. It only sees exceptions from that controller class and its subclasses. The next chapter covers sharing handlers across controllers with @RestControllerAdvice.
A first handler
This controller replaces the one from earlier chapters. It throws OrderNotFoundException and handles it locally.
package com.example.orders;
import java.util.Map;
import org.springframework.http.HttpStatus;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
record Order(long id, String item) {}
record ApiError(String code, String message) {}
@RestController
@RequestMapping("/orders")
class OrderController {
private final Map<Long, Order> orders = Map.of(1L, new Order(1L, "Book"));
@GetMapping("/{id}")
Order get(@PathVariable long id) {
Order order = orders.get(id);
if (order == null) {
throw new OrderNotFoundException(id);
}
return order;
}
@ExceptionHandler(OrderNotFoundException.class)
ResponseEntity<ApiError> handleNotFound(OrderNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ApiError("ORDER_NOT_FOUND", ex.getMessage()));
}
}A request to /orders/99 now returns status 404 and this body:
{"code":"ORDER_NOT_FOUND","message":"Order 99 was not found"}The handler receives the exception as a parameter, so it can read getOrderId() or the message without parsing anything.
Setting the status
A handler does not set a status by itself. If it returns a plain object, Spring answers 200 OK. This is the most common mistake with @ExceptionHandler, because the client sees an error body with a success code.
You have two ways to set the status:
- Return a
ResponseEntity, as above. This is the better choice when the status depends on runtime data. - Annotate the handler with
@ResponseStatus, which works when the status is fixed.
package com.example.orders;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
@RestController
class ParsingDemoController {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
ApiError handleBadParameter(MethodArgumentTypeMismatchException ex) {
return new ApiError("BAD_PARAMETER",
"Parameter '" + ex.getName() + "' has an invalid value");
}
}Handlers also catch exceptions that Spring itself throws while preparing the call. A request to /orders/abc fails during argument conversion, before your method runs. That exception is a MethodArgumentTypeMismatchException, and a local handler can handle it like any other.
What a handler method can accept and return
The exception is only one of several arguments Spring can supply.
| Kind | Examples |
|---|---|
| Exception parameter | The thrown exception, or one of its causes |
| Request context | `HttpServletRequest`, `WebRequest`, `HttpSession`, `Principal`, `Locale` |
| Return value | `ResponseEntity<T>`, any object written as the body, `ProblemDetail`, `ErrorResponse`, or `void` with `@ResponseStatus` |
For example, a handler can include the request path in the body:
@ExceptionHandler(OrderNotFoundException.class)
ResponseEntity<ApiError> handleNotFound(OrderNotFoundException ex, HttpServletRequest request) {
String message = ex.getMessage() + " (" + request.getRequestURI() + ")";
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ApiError("ORDER_NOT_FOUND", message));
}This needs import jakarta.servlet.http.HttpServletRequest;. A Model parameter is not allowed. Returning ProblemDetail is covered in a later chapter.
Declaring several exception types
The annotation takes an array. List more than one type to share one response:
@ExceptionHandler({OrderNotFoundException.class, CustomerNotFoundException.class})
ResponseEntity<ApiError> handleMissing(RuntimeException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ApiError("NOT_FOUND", ex.getMessage()));
}The method parameter must be a type that all listed exceptions share. Here RuntimeException works. If you leave the annotation's value empty, Spring uses the exception types in the method's parameter list instead. Listing the types explicitly is clearer.
How Spring picks a handler
Spring collects every @ExceptionHandler method in the controller class, including methods inherited from a superclass. For a thrown exception it applies these rules:
- It looks for handlers whose declared type matches the exception. If several match, the one closest in the class hierarchy wins. A handler for
OrderNotFoundExceptionbeats one forRuntimeException, which beats one forException. - If nothing matches, it repeats the search on the exception's cause, then that cause's cause, down the chain.
- If still nothing matches, the exception goes to the next resolver in the chain, as described in the earlier chapter on exception resolution.
Step 2 matters for wrapped exceptions. If a service wraps your exception in a RuntimeException, a handler for the inner type is still found, and the handler's parameter receives the cause.
Local handlers are consulted before @ControllerAdvice handlers. A controller can override a global rule for its own endpoints, but a matching local handler hides the global one completely, even if the global one is more specific.
Two handlers for the same type
Declaring two methods in one class for the same exception type is ambiguous. Spring fails with an IllegalStateException whose message starts with "Ambiguous @ExceptionHandler method mapped". The check runs when Spring first builds the handler table for that controller. That happens the first time an exception reaches the controller, not at startup, so a unit test that triggers an exception is the reliable way to catch the mistake.
Two handlers for different types, one a subclass of the other, are fine. The closest match rule resolves them.
A catch-all handler in a controller
A handler for Exception.class gives the controller a fallback for anything unexpected:
@ExceptionHandler(Exception.class)
ResponseEntity<ApiError> handleUnexpected(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(new ApiError("INTERNAL_ERROR", "An unexpected error occurred"));
}Limits of local handlers
Local handlers do not see every failure.
- They only handle exceptions thrown while that controller's handler method is being resolved and invoked. This includes argument binding,
@Validfailures and the method body. - Request mapping failures such as
HttpRequestMethodNotSupportedExceptionhappen before any controller is chosen. Local handlers cannot see these, but@ControllerAdvicehandlers can. - Exceptions thrown in servlet filters, including Spring Security filters, never reach
@ExceptionHandlermethods. - If the response is already committed (partly streamed to the client), the handler cannot change the status. The client sees a truncated response.
- If your handler throws an exception, Spring logs it and passes the original exception to the remaining resolvers. Keep handlers simple and free of calls that can fail.
Local or global?
| Question | Local handler | Global handler |
|---|---|---|
| Where does it live? | In the controller class | In a `@RestControllerAdvice` class |
| Which controllers does it affect? | That controller and its subclasses | All controllers by default |
| Priority | Checked first | Checked after local handlers |
| Best for | Behaviour unique to one controller | A consistent error contract for the whole API |
Local handlers suit exceptions that mean something only in one controller. If you copy the same handler into a second controller, move it to a global handler.
Exercise
A controller has @ExceptionHandler(OrderNotFoundException.class) returning new ApiError("ORDER_NOT_FOUND", ex.getMessage()) directly, with no ResponseEntity and no @ResponseStatus. What status does the client receive, and how do you fix it?
Show answer
The client receives 200 OK, because a handler that returns a plain object does not set an error status. Fix it by returning ResponseEntity.status(HttpStatus.NOT_FOUND).body(...), or by adding @ResponseStatus(HttpStatus.NOT_FOUND) to the handler method.
Exercise
A controller has handlers for RuntimeException and OrderNotFoundException (a subclass of RuntimeException). A request throws OrderNotFoundException. Which handler runs, and what happens if a @RestControllerAdvice also declares a handler for OrderNotFoundException?
Show answer
The OrderNotFoundException handler in the controller runs, because Spring picks the closest type match. The advice handler is never used for this controller, because local handlers are consulted before @ControllerAdvice handlers and a local match ends the search.