Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

API
APIs: REST & GraphQL
0/11 completed
Beginner
What is an API?HTTP methods, status codes and headersJSON
Intermediate
REST design principlesErrors and validationPagination, filtering and sortingGraphQL basics
Advanced
Versioning and cachingRate limiting and idempotencyOpenAPI documentation
Pro
Webhooks, real-time APIs and API security
Tracks / APIs: REST & GraphQL / Intermediate

Errors and validation

Clients spend more time handling your errors than you'd think. Good error responses use the right status code, follow one consistent format, explain what went wrong and how to fix it, and never leak internal details.

A bad error and a good error

json
HTTP/1.1 200 OK
{ "success": false, "msg": "error" }

That's a 200 for a failure, a vague message, and a made-up format. Compare:

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

{
  "type": "https://api.myshop.example/errors/validation",
  "title": "Your request has invalid fields",
  "status": 422,
  "detail": "2 fields failed validation",
  "instance": "/orders",
  "errors": [
    { "field": "items[0].qty", "message": "Must be between 1 and 10" },
    { "field": "email", "message": "Invalid email address" }
  ]
}

Problem Details (RFC 9457)

The second example follows Problem Details for HTTP APIs (RFC 9457), a standard JSON error format used by Spring Boot, ASP.NET and many public APIs. Its fields:

Field Meaning
type A URI identifying the kind of error (can link to documentation)
title A short, human-readable summary of that kind of error
status The HTTP status code, repeated for convenience
detail An explanation of this particular occurrence
instance The request path, or an ID for this occurrence
anything else Extra fields, e.g. errors for field-level validation

Its media type is application/problem+json. Using a standard means client libraries and tools can understand your errors without custom code.

Implementing it in Express

Throw typed errors anywhere in your code, and let one error handler turn them into Problem Details:

Node.js · editable

Look at what happened to the invalid JSON body: express.json() threw a parsing error with status: 400, and the same handler formatted it. And the database failure was logged on the server but the client only got a generic message: the internal IP address and port never left the server.

400 or 422?

Both are used for invalid input, and teams differ. A common convention:

Status When
400 Bad Request The request can't be understood: malformed JSON, wrong content type, missing required query parameter
422 Unprocessable Content The request is well-formed, but its content fails validation: an invalid email, quantity out of range
409 Conflict It's valid, but conflicts with the current state: duplicate username, item already sold out

Pick one convention, document it, and apply it everywhere.

Validate at the edge

Check input as soon as it enters your system (in the route or a middleware), then pass only clean, typed data to the rest of your code. Validate:

  • Types and formats: numbers are numbers, emails are emails, dates parse.
  • Ranges and lengths: quantity 1–10, names up to 100 characters, page sizes up to 100.
  • Allowed values: status is one of a known list.
  • Unknown fields: strip or reject them, so clients can't set isAdmin or price.
  • Business rules: the coupon exists and hasn't expired, the product is in stock (often 409 or 422).

Never trust validation done in the browser: anyone can call your API directly.

Error-handling checklist

  • Use the right status code; never 200 with "success": false.
  • Use one error format everywhere (Problem Details is a good default).
  • Write messages for the developer reading them: say what was wrong and what's expected.
  • Include a stable machine-readable type or code ("insufficient_funds") that clients can switch on, since messages may change.
  • Return all validation errors at once, not one per request.
  • Log the details of 5xx errors with a request ID; return the request ID to the client so support can find the log.
  • Never expose stack traces, SQL, file paths or internal hostnames.

Practice

  1. Add a stable code field to the problem responses (validation_failed, not_found, internal_error).
  2. Generate a request ID for every request (crypto.randomUUID()), log it with 500 errors and return it in an X-Request-Id header.
  3. Add a business rule to POST /orders: if a productId is 999, respond with 409 and title: "Out of stock".
✎ Check your understanding

1.What's wrong with returning 200 OK and {"success": false} for errors?

2.What should a 500 response tell the client?

3.What media type does RFC 9457 define for error responses?

← REST design principles