Exception Handling
Errors are part of your API. A client should receive a consistent JSON body with a meaningful status code — not a stack trace, and not a different format from every endpoint. Spring gives you @ExceptionHandler for one controller, @RestControllerAdvice for the whole application, and ProblemDetail, the standard error format of RFC 9457.
Domain exceptions
Start with exceptions that describe what went wrong in business terms:
public class TaskNotFoundException extends RuntimeException {
public TaskNotFoundException(long id) { super("Task " + id + " not found"); }
}
public class DuplicateTitleException extends RuntimeException {
public DuplicateTitleException(String title) { super("A task titled '" + title + "' already exists"); }
}The service simply throws them; it knows nothing about HTTP:
Task get(long id) {
return repository.findById(id).orElseThrow(() -> new TaskNotFoundException(id));
}A global handler with ProblemDetail
@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(TaskNotFoundException.class)
ProblemDetail notFound(TaskNotFoundException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
pd.setTitle("Task not found");
pd.setType(URI.create("https://api.example.com/problems/task-not-found"));
return pd;
}
@ExceptionHandler(DuplicateTitleException.class)
ProblemDetail conflict(DuplicateTitleException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
}
@Override // validation errors from @Valid @RequestBody
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail pd = ex.getBody(); // already 400 / "Invalid request content."
Map<String, String> errors = new TreeMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(fe -> errors.put(fe.getField(), fe.getDefaultMessage()));
pd.setProperty("errors", errors); // extra member in the JSON
return ResponseEntity.status(status).body(pd);
}
}| Piece | Role |
|---|---|
@RestControllerAdvice |
applies the handlers to every controller; results are written as the body |
@ExceptionHandler(X.class) |
handles X and its subclasses |
ResponseEntityExceptionHandler |
base class that already maps Spring MVC's own exceptions (405, 415, 400…) to ProblemDetail |
ProblemDetail |
serialised as application/problem+json |
curl -s -i localhost:8080/api/tasks/99HTTP/1.1 404
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Thu, 16 Oct 2025 04:20:11 GMT
{"type":"https://api.example.com/problems/task-not-found","title":"Task not found","status":404,"detail":"Task 99 not found","instance":"/api/tasks/99"}
curl -s -X POST localhost:8080/api/tasks -H "Content-Type: application/json" -d '{"title":""}' | jq{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Invalid request content.",
"instance": "/api/tasks",
"errors": {
"priority": "must not be null",
"title": "must not be blank"
}
}
The ProblemDetail fields
| Field | Meaning |
|---|---|
type |
URI identifying the problem type (about:blank = just the status) |
title |
short, human-readable summary of the type |
status |
the HTTP status code |
detail |
explanation specific to this occurrence |
instance |
URI of this occurrence (Spring fills in the request path) |
| extra properties | anything you add with setProperty |
How handler lookup works
When an exception escapes a controller, Spring searches for the handler whose declared type is the closest superclass of the thrown exception. A catch-all Exception handler therefore only gets what nothing more specific handles. This plain-Java model reproduces that lookup:
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
class TaskNotFoundException extends RuntimeException {
TaskNotFoundException(long id) { super("Task " + id + " not found"); }
}
class DuplicateTitleException extends RuntimeException {
DuplicateTitleException(String t) { super("A task titled '" + t + "' already exists"); }
}
record Problem(int status, String title, String detail) {
String toJson(String path) {
return "{\"title\":\"" + title + "\",\"status\":" + status
+ ",\"detail\":\"" + detail + "\",\"instance\":\"" + path + "\"}";
}
}
class Advice {
private final Map<Class<? extends Throwable>, Function<Throwable, Problem>> handlers = new LinkedHashMap<>();
<E extends Throwable> void on(Class<E> type, Function<Throwable, Problem> h) { handlers.put(type, h); }
Problem handle(Throwable ex) {
for (Class<?> c = ex.getClass(); c != null; c = c.getSuperclass()) { // closest type first
var h = handlers.get(c);
if (h != null) return h.apply(ex);
}
throw new IllegalStateException("unhandled", ex);
}
}
class Main {
public static void main(String[] args) {
Advice advice = new Advice();
advice.on(TaskNotFoundException.class, e -> new Problem(404, "Task not found", e.getMessage()));
advice.on(DuplicateTitleException.class, e -> new Problem(409, "Conflict", e.getMessage()));
advice.on(IllegalArgumentException.class, e -> new Problem(400, "Bad Request", e.getMessage()));
advice.on(Exception.class, e -> new Problem(500, "Internal Server Error", "Unexpected error"));
RuntimeException[] thrown = {
new TaskNotFoundException(99),
new DuplicateTitleException("Ship v1"),
new NumberFormatException("not a number: x"), // subclass of IllegalArgumentException
new NullPointerException("secret internal detail")};
for (RuntimeException ex : thrown) {
System.out.println(advice.handle(ex).toJson("/api/tasks"));
}
}
}{"title":"Task not found","status":404,"detail":"Task 99 not found","instance":"/api/tasks"}
{"title":"Conflict","status":409,"detail":"A task titled 'Ship v1' already exists","instance":"/api/tasks"}
{"title":"Bad Request","status":400,"detail":"not a number: x","instance":"/api/tasks"}
{"title":"Internal Server Error","status":500,"detail":"Unexpected error","instance":"/api/tasks"}
NumberFormatException has no handler of its own, so the IllegalArgumentException handler (its superclass) wins. The NullPointerException falls through to the catch-all, which deliberately hides the internal message.
Other options
@ResponseStatuson an exception class —@ResponseStatus(HttpStatus.NOT_FOUND) class TaskNotFoundException ...— quick, but you cannot customise the body.ResponseStatusException— thrownew ResponseStatusException(HttpStatus.NOT_FOUND, "...")without defining a class.ErrorResponseException— a base class for your own exceptions that carry aProblemDetail.
Tip: Always log unexpected exceptions (
log.error("Unhandled", ex)) in the catch-all handler, but never send their message or stack trace to the client — they can reveal SQL, file paths or library versions.
Test yourself
What does @RestControllerAdvice do?
- Adds security to controllers
- Declares exception handlers (and other advice) that apply to all controllers
- Generates API documentation
- Validates request bodies
Which media type does Spring use when a handler returns ProblemDetail?
application/jsonapplication/problem+jsontext/plainapplication/error
Handlers exist for IllegalArgumentException and Exception. A NumberFormatException is thrown. Which handler runs?
ExceptionIllegalArgumentException- Both
- None