Sub topic 1
Why error handling deserves a design
Every API fails sometimes. A client asks for an order that does not exist, sends a body with a blank field, or hits a server whose database is down. What the API sends back in those moments is part of its contract, just like the success responses. This chapter explains why that contract needs a deliberate design, and it sets up the rest of the tutorial.
Prerequisites
This chapter assumes you already have the following.
- Basic Java, including the difference between checked and unchecked exceptions.
- Experience building a simple REST controller with Spring Boot.
- Familiarity with HTTP status codes and JSON responses.
- Basic Maven or Gradle usage, enough to add a dependency.
You do not need to know anything about @ExceptionHandler, @RestControllerAdvice or ProblemDetail. The later chapters introduce them one at a time.
Errors are part of the API
A client developer reads your API documentation for the success case. In production, they spend much of their time on the failure cases. They need to answer questions like these:
- Was the request wrong, or is the server broken? Should I fix my input or retry later?
- Which field was invalid, and why?
- Is it safe to show this message to an end user?
- What do I log or report so that support can find the problem?
If your API answers these questions in a different way on every endpoint, each client needs special-case code for every endpoint. A consistent error contract removes that work. It also helps you, because the server code that produces errors lives in one place instead of being scattered across controllers.
What goes wrong without a design
When nobody designs error handling, it grows one controller at a time. Each developer solves the immediate problem in whatever way is quickest. The following controller shows typical results.
package com.example.legacy;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
class LegacyOrderController {
private final Map<Long, String> orders = Map.of(1L, "Book");
@GetMapping("/legacy/orders/{id}")
ResponseEntity<?> get(@PathVariable long id) {
try {
String item = orders.get(id);
if (item == null) {
return ResponseEntity.status(200).body("not found");
}
return ResponseEntity.ok(Map.of("id", id, "item", item));
} catch (Exception e) {
return ResponseEntity.status(500).body(e.toString());
}
}
}This code has several problems.
- Wrong status. An unknown order returns
200 OKwith the textnot found. A client that checks status codes treats a failure as a success. - Mixed body types. The success body is a JSON object, but the failure body is a plain string. A client cannot parse both with one model.
- Leaked internals.
e.toString()sends the exception class name and message to the client. This can expose table names, file paths or library versions. - Repeated try/catch. Every endpoint needs the same block, and each copy can drift away from the others.
- No logging. The catch block hides the exception from the server logs. Nobody on the team learns that something failed.
None of these problems shows up in a happy-path test. They appear only when something goes wrong in production, which is the worst time to find out.
Properties of a good error contract
A well-designed error contract has these properties.
- Correct status codes. The status line says what class of problem occurred.
4xxmeans the client can change the request to fix it.5xxmeans the server failed. - One body shape. Every error response has the same structure, so clients write one parser.
- Machine-readable and human-readable parts. A stable field such as a type or a code lets programs branch. A readable message lets people understand.
- Field-level detail for validation. When several fields are wrong, the response lists each one, so a user can fix them in one attempt.
- No internal details. The response never contains stack traces, SQL, or class names. Those go to the server log.
- Traceable failures. Every unexpected error is logged once, with enough context to diagnose it.
- Testable behavior. Tests assert the status and body of error responses, so the contract does not change by accident.
The table maps each property to the chapter of this tutorial that covers the mechanism. The chapter names match the plan for the whole tutorial.
| Property | Where it is covered |
|---|---|
| Correct status codes | Custom exceptions, `@ResponseStatus`, `ResponseStatusException` |
| One body shape | `@RestControllerAdvice` and `ProblemDetail` |
| Machine- and human-readable parts | `ProblemDetail` (RFC 9457) |
| Field-level detail | Bean Validation handling |
| No internal details | `server.error.*` properties and error-response security |
| Traceable failures | Logging errors without noise or duplication |
| Testable behavior | Testing with MockMvc |
The shape of the solution
The approach used in the rest of the tutorial separates three jobs that the legacy controller mixed together.
- Detecting the failure. Business code throws an exception that names the problem, for example
OrderNotFoundException. It does not decide the HTTP response. - Translating the failure. A central component maps each exception type to a status code and a body.
- Recording the failure. The same central component logs unexpected errors, and a test suite checks the outcome.
Controllers and services stay focused on business rules. The HTTP details of failure live in one place.
What Spring Boot gives you for free
You do not start from nothing. If you add no error code at all, Spring Boot still turns an uncaught exception into a response. It maps the failure to a status code and renders a JSON body with fields such as timestamp, status, error and path. An unhandled exception becomes a 500. A request for a URL with no matching mapping becomes a 404.
{
"timestamp": "2026-12-01T10:13:30.605+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/orders/7"
}This default is a reasonable safety net, and the next chapter examines how it works. It is not a design, for these reasons:
- Every unexpected exception becomes a
500, even when the real cause is a missing record that should be a404. - The body has Boot's own shape, which you do not control or document as part of your API.
- It has no place for field-level validation detail or for domain data such as the order id.
The design work is to decide what you want instead, and then to configure Spring to produce it.
Choosing status codes: a first pass
Mapping failures to statuses is the first design decision. These are the codes you will use most in a typical REST API.
| Situation | Status | Typical cause |
|---|---|---|
| Malformed or invalid input | `400 Bad Request` | Failed Bean Validation, unreadable JSON |
| Resource does not exist | `404 Not Found` | Unknown order id |
| State conflicts with the request | `409 Conflict` | Duplicate create, stale update |
| Unexpected server failure | `500 Internal Server Error` | Bug, database outage |
Two rules help when a case is unclear. First, prefer the most specific code that is accurate. Second, never use 200 for a failure, because caches, proxies and client libraries all treat 2xx as success.
Common design mistakes
These mistakes appear often in real projects, and the rest of the tutorial helps you avoid each of them.
- Catching
Exceptionin controllers. It hides bugs and forces every method to repeat the same block. Let exceptions propagate to a central handler. - Returning the exception message directly. Messages written for developers can reveal internals. Write client-facing text on purpose.
- Logging at every layer. If the service logs an exception, rethrows it, and the controller logs it again, one failure appears several times in the logs. Choose one place to log.
- Treating validation failures as server errors. Bad input is a client mistake, so it needs a
4xxand a clear explanation. - Changing the body shape between endpoints. Once clients depend on a shape, changing it is a breaking change, just as for success responses.
How this tutorial builds the contract
The chapters follow the order in which the problem usually grows.
- Look at what Spring Boot does by default and how to tune it.
- Model failures as domain exceptions and map them to statuses.
- See how Spring MVC resolves an exception into a response.
- Use quick mappings, local handlers, and then one global
@RestControllerAdvice. - Standardize the body with
ProblemDetail, and report validation failures field by field. - Add logging, keep internals out of responses, and test it all with MockMvc.
- Finish with how Spring WebFlux differs.
By the end, a single handler class and a handful of exception types produce every error your API returns, and tests keep that behavior stable.
Exercise
A client calls GET /legacy/orders/99 on the controller shown earlier in this chapter. The order does not exist. Name three problems with the response the client receives, and say which property of a good error contract each one violates.
Show answer
The response is a 200 OK status with the plain-text body "not found". (1) The status is 200 instead of 404, which violates the "correct status codes" property, because clients and proxies treat 2xx as success. (2) The body is a plain string, while the success body is a JSON object, which violates the "one body shape" property. (3) The body has no stable machine-readable field and no domain detail such as the order id, which violates the "machine-readable and human-readable parts" property. Separately, the same controller's catch block returns e.toString() and does not log, which breaks the "no internal details" and "traceable failures" properties.
Exercise
A service method logs an exception with log.error and rethrows it. The controller that called it also catches the exception and logs it with log.error. What is the effect in production, and what is the design fix?
Show answer
One failure produces two (or more) log entries with the same stack trace, which adds noise and can make one incident look like several. The fix is to choose one place to log. In the design built in this tutorial, that place is the central exception handler, so services and controllers let the exception propagate without logging it.