Lesson 19 / 25
Standard Error Responses
Return one consistent error format with stable machine-readable codes, and never leak stack traces to clients.
One shape for every failure
Whatever goes wrong — validation, auth, a server crash — the error body should have the same structure, so clients can write one error-handling path instead of one per endpoint.
A reusable envelope
A machine-readable code, a human message, and optional details for field-level problems.
HTTP/1.1 422 Unprocessable Entity
{
"error": {
"code": "VALIDATION_FAILED",
"message": "Request has invalid fields.",
"details": [
{ "field": "email", "issue": "must be a valid email address" }
]
}
}Codes for machines, messages for humans
Clients should branch on error.code (a stable string), never on parsing error.message; message text can change without warning. Consider the standard Problem Details format (RFC 9457, application/problem+json).
Don't leak internals
Never put a stack trace, SQL query, or file path in a client-facing error — log those server-side against a requestId, and return only that id to the client for support to trace.