Error Handling, Validation and API Hardening

Make APIs fail safely: validate every input, return consistent errors, never leak internals, and protect against abuse.

Intermediate · about 5 hours · difficulty 3/5

Learn first: REST API Design, Runtime Validation with Zod

Production APIs spend much of their code on things that go wrong. Doing this well separates a demo from a real product.

Validation at the edge

Validate body, params and query with Zod before any business logic runs. Reject unknown fields where it matters, coerce query strings to numbers deliberately, and return 400 with field-level messages.

A single error strategy

  • Define a small set of error classes (NotFound, Conflict, Forbidden, Validation) that carry a status and a code.
  • Throw them from services; translate them to HTTP in one place (error middleware or a handler wrapper).
  • Log the full error with a request id on the server; send the client a safe message and the request id.

Hardening

  • Rate limiting on login, OTP and signup endpoints.
  • Request size limits and timeouts.
  • Idempotency for operations like "create payment order" so retries do not double-charge.
  • Avoid exposing stack traces, SQL errors or internal ids in responses.

Pitfalls

  • try/catch in every handler with copy-pasted responses.
  • Returning 500 for user mistakes, which pollutes alerting.
  • Catching errors and silently ignoring them.

You are ready to move on when every endpoint in your API returns the same error shape, bad input never reaches the database, and a forced crash returns a safe message with a request id that you can find in the logs.

Key concepts

  • Validating body, params and query
  • Custom error classes
  • Central error translation
  • Request ids
  • Rate limiting
  • Size limits and timeouts
  • Idempotent operations

Mini project

Refactor your API so all routes use shared validation middleware and typed error classes, add request ids to logs and responses, and rate limit the auth endpoints. Write a short table of every error code your API can return.

Check yourself

A database unique constraint fails when a student applies twice. What status code and response should the client get, and what should go in the logs?

Free resources