Lesson 18 / 24

Standard Error Responses

Giving every error the same predictable shape and useful codes.

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 wording without warning, breaking any logic tied to it.

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.