Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Designing Resources and Endpoints

Designing Error Responses

Design useful REST API errors: consistent JSON, application/problem+json (RFC 9457), validation error lists, error codes, request ids and not leaking internals.

Every API fails sometimes: the input is wrong, the item does not exist, the database is down. What distinguishes a pleasant API from a frustrating one is what the failure looks like. A client developer staring at 500 {"error":"error"} loses an hour. One who gets a precise status, a machine-readable code and a human-readable explanation fixes the problem in a minute.

Errors need three properties: consistent (always the same shape), actionable (tell the client what to change) and safe (never leak stack traces, SQL or file paths).

Status code first, body second

The HTTP status code is the primary signal (see status codes). The body adds detail. Never return 200 with an error inside, and never use 500 for mistakes the client made.

A minimal custom error body might be:

JSON
{
  "error": {
    "code": "validation_failed",
    "message": "The request body is invalid.",
    "details": [
      { "field": "email", "message": "must contain @" }
    ],
    "requestId": "req_8f3a"
  }
}

The code is a stable, machine-readable string clients can branch on (email_taken, rate_limited). The message is for humans and may change or be translated. Clients should never parse the message.

Problem Details: the standard format

RFC 9457 (which replaces RFC 7807) defines a standard JSON error format, application/problem+json. Because it is a standard, client libraries and API gateways understand it. The members are:

Member Meaning
type A URI identifying the kind of problem (can point to documentation). Default about:blank
title Short, human-readable summary of the type. Same for every occurrence
status The HTTP status code, repeated for convenience
detail Explanation of this occurrence
instance A URI identifying this specific occurrence (e.g. the request id)

You can add extension members, such as errors for validation failures:

HTTP
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Your request parameters didn't validate.",
  "status": 422,
  "detail": "2 fields are invalid.",
  "instance": "/requests/8f3a",
  "errors": [
    { "pointer": "/email", "message": "must contain @" },
    { "pointer": "/age", "message": "must be at least 18" }
  ]
}

Using JSON Pointer (/email) for the location of the invalid field is a tidy convention. You may use field names instead; the important part is consistency.

Validation errors: report all of them

When a form has five invalid fields, returning only the first makes the client fix, resubmit, fail, fix, resubmit... Collect all problems and return them in one response. Validation and Input Handling builds the validator that produces such a list.

What not to reveal

  • No stack traces, file paths, SQL, framework names or versions in responses. Log them on the server, tied to a request id.
  • For authentication failures, do not say which part was wrong: "Invalid email or password" never "No such user".
  • A 404 can deliberately hide that a resource exists but is forbidden (see authentication vs authorization).
  • For 500, a short generic message and the request id are enough. The client can quote the id to support, who looks it up in the logs.
flowchart LR
    A["Error thrown in handler"] --> B{"Known, expected error?"}
    B -- "Yes: validation, not found, conflict" --> C["4xx with specific details"]
    B -- "No: bug, crash" --> D["Log full details + request id"]
    D --> E["500 with generic message + request id"]

Expected errors are explained; unexpected ones are logged, not exposed.

Problem details in practice

The server below returns application/problem+json from one central function, problem(). The client reads the content type, branches on status and prints each member.

Node.js Problem Details responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the /crash call: the secret message appears only in the server log line, while the client received a generic body with an instance id.

An error class for handlers

Throwing errors from deep inside a handler and mapping them to responses in one place keeps code clean. Define an error type that carries a status and optional details, then catch it centrally. This is exactly the pattern Middleware and Error Handling builds into a real pipeline.

Node.js An HttpError class and one central mapper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The TypeError (a genuine bug) becomes a bland 500, while the deliberate HttpErrors keep their precise status and message.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the media type for standardized problem details responses?

    RFC 9457 (formerly 7807) defines application/problem+json.
  2. 2. Why should clients branch on an error code, not on the message text?

    A machine-readable code is part of the contract; the message is not.
  3. 3. What should a 500 response body contain?

    Never leak internals. Log them, and give the client an id to quote.
  4. 4. A form submission has four invalid fields. How should the API respond?

    One response listing every problem saves the client from repeated round trips.
  5. 5. A login fails. Which message is best?

    Do not reveal which part was wrong, so attackers cannot discover which emails are registered.

Summary

  • Always use the right status code and add a consistent, structured body.
  • Prefer application/problem+json (type, title, status, detail, instance) and extend it with an errors list for validation.
  • Provide stable machine-readable codes; messages are for humans.
  • Return all validation errors at once, and never expose stack traces, SQL or account existence.
  • Throw typed errors in handlers and map them to responses in one central place.

Next: Relationships, Sub-resources and Actions