Card 01/ 07

ConceptDifficulty: Intermediate1 min

Consistent Error Handling in a REST API

What an API looks like when each endpoint invented its own failures, and the three things that fix it.

Consistent error handling means every failure in an API reaches the client in the same way: a status code that says what kind of failure it was, and a body in one agreed shape. In Spring Boot it rests on three things: an exception type for each kind of failure, one place that turns each exception into a response, and one shape for the response body.

Without it, an API accumulates. One endpoint returns a JSON object naming the problem. Another returns a bare 500 with a stack trace (the list of method calls at the moment of failure) leaked into the body. A third returns 200 with an error message buried inside what looks like a success. None of it was decided; each endpoint's error handling was added when it first broke in production.

A client of that API has to handle three formats and cannot trust the status code, so every new endpoint means new client code. The leaked stack trace is worse: it tells anyone who calls the endpoint which libraries and classes the server runs.

The three parts map directly onto Spring features. A custom exception class names each kind of failure. An @ExceptionHandler method, a method Spring calls when a given exception is thrown, turns one exception type into one response, and @RestControllerAdvice gathers those methods in one class that applies to every controller. The body shape is whatever those methods return, written once.

So consistency is a design decision made once, not a fix applied endpoint by endpoint: decide the failures, the statuses and the body, and every controller gets them for free.