Skip to the page

HTTP semantics, caching and delivery · core

Status codes and handling HTTP errors with fetch

Status codes tell the client what happened (2xx success, 3xx redirect or not-modified, 4xx the client's fault, 5xx the server's fault), and fetch only rejects on network failure or abort, so your code must check response.ok and handle each class differently.

The notes

What you must know

  • Common codes: 200 OK, 201 Created, 204 No Content (no body), 301/308 permanent redirect, 302/307 temporary (307/308 keep the method), 303 See Other (go GET), 304 Not Modified (use your cached copy).
  • 4xx: 400 bad request, 401 not authenticated (log in / refresh token), 403 authenticated but not allowed, 404 not found, 409 conflict (stale version), 422 validation failed, 429 too many requests (read Retry-After).
  • 5xx: 500 server bug, 502 bad gateway, 503 unavailable (often with Retry-After), 504 gateway timeout. These are usually retryable for idempotent requests.
  • fetch() resolves for 404 and 500. It rejects only for network errors, CORS failures and abort. Always check res.ok (status 200 to 299).
  • Parsing: a 204 or an HTML error page from a proxy breaks res.json(); check the status and Content-Type first.
  • Build one API client: check ok, parse safely, map errors to typed objects (auth, validation, not found, rate limit, server, network), log details, and show the user a helpful message.

The red pen

Common traps: mistake → fix

  • Mistake: "fetch throws on 4xx and 5xx"

    Fix: it resolves; only network errors and aborts reject.

  • Mistake: "401 and 403 mean the same thing"

    Fix: 401 means not authenticated; 403 means authenticated but not allowed.

  • Mistake: "Every error can be retried"

    Fix: 4xx (except 408 and 429) will fail again; retry only transient errors.

Easy to hard

Questions interviewers ask, easy to hard

  1. Name the status codes you handle in a UI and what the UI does for each.
  2. Why does this fetch helper return undefined / not throw on 404?
  3. 401 vs 403 vs 404 for a resource the user may not see: which would you return and why?
  4. Design the error-handling layer of your API client.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview