Sub topic 1
Why error handling deserves a design
Every REST API fails sometimes. A client sends a bad body, asks for an order that does not exist, or hits a bug on the server. What the API returns in those moments is part of its public contract, just like the success responses. This chapter explains why that contract needs a deliberate design and sets up the rest of the tutorial.
Prerequisites
This chapter assumes you have:
- Basic Java, including the difference between checked and unchecked exceptions.
- A simple Spring Boot REST controller that you have built and run.
- Working knowledge of HTTP status codes and JSON responses.
- Basic Maven or Gradle usage.
What goes wrong without a design
If you do nothing, Spring Boot still returns something for every failure. The result is often inconsistent. Consider a controller that looks up an order:
package com.example.orders;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
class NaiveOrderController {
private final Map<Long, String> orders = Map.of(1L, "Book");
@GetMapping("/naive-orders/{id}")
String get(@PathVariable long id) {
return orders.get(id).toUpperCase();
}
}A request for an unknown id makes orders.get(id) return null. The call to toUpperCase() then throws a NullPointerException. The client receives a generic 500 response. That tells the client the server is at fault, when the real problem is that the order does not exist. The client cannot tell the two apart, so it cannot react sensibly.
Common symptoms of an undesigned error path:
- The wrong status code, such as 500 for a missing resource.
- Different body shapes from different endpoints, so clients need special parsing for each.
- Messages written for developers that reach end users.
- Internal details such as class names or stack traces visible to anyone who calls the API.
- The same failure logged several times, or not at all.
What a good error contract provides
A well-designed error path gives callers four things.
- A correct status code. 4xx means the client can fix the request. 5xx means the server failed.
- One body shape. Every error uses the same fields, so clients write one parser.
- Useful detail. The body says what went wrong and, for validation, which fields.
- Safety. Nothing internal leaks, and the server still records the full cause for you.
The standard format this tutorial builds toward is RFC 9457 "problem details". Spring represents it with the ProblemDetail class, which you will use in a later chapter.
The path an error takes
An exception thrown in a controller does not go straight to the client. Spring MVC intercepts it and decides what response to produce. The pieces you will meet, in order, are shown below.
The default branch works but gives you no control. The custom branch is where you design the contract.
Roadmap for this tutorial
The chapters that follow move from the default behavior toward one consistent contract:
| Stage | Topic |
|---|---|
| Defaults | What Spring Boot returns and how `server.error.*` properties tune it |
| Modeling | Custom exceptions that describe domain failures |
| Mapping | `@ResponseStatus`, `ResponseStatusException`, `@ExceptionHandler` |
| Centralizing | `@RestControllerAdvice` and `ProblemDetail` |
| Hardening | Validation errors, logging, and keeping details out of responses |
| Verifying | Tests with MockMvc, and a note on WebFlux |
By the end you will have one error contract that every endpoint in your API follows.
Exercise
A client requests an order that does not exist and receives a 500 response with a generic body. Name two problems with this from the client's point of view, and the status code that fits better.
Show answer
The status code wrongly says the server failed, so the client may retry pointlessly, and the generic body gives no hint that the order id was the problem. A 404 Not Found fits better, ideally with a body that names the missing order.
Exercise
Why is it a problem if each endpoint returns its own error body shape?
Show answer
Clients must write separate parsing code for each endpoint, and new endpoints risk adding yet another shape. A single shared structure lets clients handle all errors the same way.