One error shape, everywhere
When something goes wrong, a lazy API returns a bare string, a different JSON shape per endpoint, or worse, a 200 with "error" hidden inside. Clients then need special handling for every case.
Great APIs pick one error shape and use it for every failure:
{
"error": {
"code": "user_not_found",
"message": "No user with id 42",
"details": []
}
}code: a stable, machine-readable string. Client code branches on this, never on the message.message: a human-readable explanation for developers and logs.details: optional specifics, like which fields failed validation.
The status code (lesson 3-3) says what family of problem, the body says exactly which one.
Code exercise · javascript
Run this error factory. Every failure in the API goes through one function, so the shape can never drift between endpoints.
Quiz
Why should client code branch on error.code ("user_not_found") instead of the message text?
Code exercise · javascript
Your turn. Complete validateSignup. Collect a details entry for each broken field: email must contain "@", password must be at least 8 characters. No problems: return { status: 200, body: { ok: true } }. Any problems: status 400 with code "invalid_input" and the details array.
Quiz
A teammate's endpoint catches every failure and responds 200 OK with { "error": "something broke" } in the body. Why is this a real problem, not a style preference?