Explain it simply
Error handling in plain language
When a call to an API fails, "it failed" is not enough information. The server may be telling you that your request is wrong (a 4xx status), or that it is broken or busy right now (a 5xx status), or you may never have reached it at all because the network dropped or the request took too long. Each of these needs a different reaction: fix the input, wait and try again, or tell the user and stop.
So a good client sorts every failure into a bucket before it acts. Status codes make that easy because the first digit is the class: 2xx means success, 4xx means the client must change something, 5xx means the server had a problem, and the cases with no status at all are network failures and timeouts.
Problem → Why → Solution
The problem: believing try/catch covers every error
The function below wraps fetch in try/catch and believes that covers every error. In fact, on a 404 it returns the error body as if it were a user. When the network drops, it retries a hundred times in a tight loop with no delay and no timeout. If a proxy sends a 502 HTML page, res.json() throws and that also lands in the retry loop. The same code that ignores real HTTP errors then hammers the server with blind retries.
async function getUser(id) {
for (let i = 0; i < 100; i++) {
try {
const res = await fetch("/v1/users/" + id);
const user = await res.json(); // 404 and 500 bodies come back as "users"
return user;
} catch (err) {
// network error or invalid JSON: retry immediately, whatever the cause
}
}
}A failure has a cause, and the cause decides the reaction
Retrying fixes temporary problems: a dropped connection, an overloaded server (503), a rate-limit window (429). It cannot fix a request that is wrong. On the hundredth attempt a 404 is still a 404 and a 422 is still a 422, and the retries only add load. So the client must look at the cause, a status code or the lack of a response, before it decides to wait, to fix or to give up.
Core concept: four outcomes, four reactions
Every fetch call ends in one of four ways. (1) A 2xx response: use the body. (2) A 4xx response: the server understood you and says the request is wrong or not allowed, so change the request. (3) A 5xx response: the server failed, and the same request may work later. (4) No response: fetch rejects with a TypeError for network failure, DNS trouble or a refused connection, and with a TimeoutError or AbortError when a time limit you set runs out. The key detail is that fetch rejects only in case 4. Cases 2 and 3 are fulfilled promises with res.ok false, so you must check res.ok yourself.
A well-designed API sends a machine-readable error body in one consistent shape, for example { "error": { "code": "validation_failed", "message": "...", "fields": { "email": "..." } } }. Branch on the stable code, not on the human message, show field messages next to the inputs, and log any request id for support. Read the body defensively: proxies and gateways often send an HTML page for 502 and 504, so call res.json() inside a catch and fall back to the status.
| Status | What it tells you | Retry? |
|---|---|---|
| 400 / 422 | Fix the request body | No |
| 401 / 403 | Fix credentials or permissions | No |
| 404 / 409 | Wrong target or state conflict | No |
| 429 | Too many requests | Yes, after Retry-After |
| 502 / 503 / 504 | Gateway failure or overload | Yes, with backoff |
| No response | Network error or timeout | Yes, if idempotent |
400 means the request could not be understood at all (broken JSON, wrong Content-Type). 422 means it was well formed but the values are unacceptable (an invalid email), usually with per-field messages. 409 means a conflict with the current state (a duplicate email). Some APIs answer 400 for everything, so check the docs. Retry only problems that can go away by themselves: network errors, timeouts, 429 and 502/503/504. Wait between attempts with exponential backoff (about 100, 200, 400 ms) and add jitter, a random amount, so that a thousand clients that failed together do not all come back in the same second. If the server sends Retry-After, a number of seconds or an HTTP date, obey it instead of guessing, and cap the number of attempts.
- No response? Network error or timeout
- 4xx? Fix the request, do not retry
- 5xx or 429? Wait with backoff, retry
- 2xx? Parse the body and use it
fetch throws only for the first kind; the other three arrive as normal responses, so res.ok and res.status are your triage tools.
General pattern
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const res = await fetch(url, { signal: AbortSignal.timeout(ms) });
if (res.ok) return await res.json();
if (!isRetryable(res.status)) throw await toApiError(res);
} catch (err) {
if (!isRetryable(err) || attempt === maxAttempts) throw err;
}
await sleep(retryAfterMs ?? randomUpTo(baseMs * 2 ** attempt));
}Each pass sends the request with a time limit, returns on success, throws at once on an error that must not be retried, and otherwise waits for Retry-After or a jittered backoff before trying again.
Worked example: one request() for every kind of failure
The sample starts a tiny local API that fails in all the ways a real one can: a 404, a 422 with field messages, a 502 with an HTML body, an endpoint that answers 503 twice before it works, a 429 with Retry-After, and an endpoint that never answers. request() turns every failure into an Error tagged with a kind (network, timeout or http), and withRetry() retries only the kinds that can go away by themselves. Retry-After is 0 seconds and the backoff is a few milliseconds, so the whole run takes under a second.
import http from "node:http";
// A stand-in API that fails in every way a real one can.
let flakyCalls = 0;
let limitedCalls = 0;
const send = (res, status, body, headers = {}) => {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(JSON.stringify(body));
};
const fail = (res, status, code, message, { fields, headers } = {}) =>
send(res, status, { error: { code, message, ...(fields && { fields }) } }, headers);
const server = http.createServer((req, res) => {
const { pathname } = new URL(req.url, "http://localhost");
if (pathname === "/v1/users/u_1") {
send(res, 200, { id: "u_1", name: "Alice" });
} else if (pathname === "/v1/users/u_99") {
fail(res, 404, "user_not_found", "No user with id u_99");
} else if (pathname === "/v1/signup") {
const fields = { email: "must be a valid email address" };
fail(res, 422, "validation_failed", "Invalid input", { fields });
} else if (pathname === "/v1/flaky") {
if (++flakyCalls < 3) fail(res, 503, "unavailable", "Try again shortly");
else send(res, 200, { ok: true });
} else if (pathname === "/v1/limited") {
// Retry-After: 0 keeps the lesson fast; real servers send seconds or a date
const headers = { "Retry-After": "0" };
if (++limitedCalls < 2) fail(res, 429, "rate_limited", "Slow down", { headers });
else send(res, 200, { ok: true });
} else if (pathname === "/v1/proxy") {
res.writeHead(502, { "Content-Type": "text/html" });
res.end("<h1>Bad Gateway</h1>");
}
// any other path (/v1/slow) never answers
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + server.address().port;
// One request() that turns every failure into an Error tagged with a kind.
async function request(url, timeoutMs = 300) {
let res;
try {
res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
} catch (cause) {
// fetch THROWS only when no HTTP response arrived at all
const kind = cause.name === "TimeoutError" ? "timeout" : "network";
throw Object.assign(new Error(kind + " failure"), { kind, cause });
}
if (res.ok) return res.json();
const body = await res.json().catch(() => ({})); // an error page may not be JSON
const { code, message, fields } = body.error ?? {};
const retryAfter = res.headers.get("retry-after");
throw Object.assign(new Error(message ?? "HTTP " + res.status), {
kind: "http",
status: res.status,
code,
fields,
retryAfterMs: retryAfter === null ? undefined : Number(retryAfter) * 1000,
});
}
const RETRYABLE = new Set([429, 502, 503, 504]);
const isRetryable = (e) =>
e.kind === "network" ||
e.kind === "timeout" ||
(e.kind === "http" && RETRYABLE.has(e.status));
async function withRetry(fn, maxAttempts = 4, baseMs = 20) {
for (let attempt = 1; ; attempt++) {
try {
return { value: await fn(), attempts: attempt };
} catch (err) {
if (!isRetryable(err) || attempt === maxAttempts) throw err;
// honour Retry-After, otherwise exponential backoff with full jitter
const wait = err.retryAfterMs ?? Math.random() * baseMs * 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, wait));
}
}
}
async function show(label, promise) {
try {
console.log(label + ":", JSON.stringify(await promise));
} catch (e) {
const parts = [e.kind];
if (e.kind === "http") parts.push(e.status, e.code ?? "(no JSON error body)");
if (e.kind === "network") parts.push(e.cause.cause?.code);
if (e.fields) parts.push(JSON.stringify(e.fields));
console.log(label + ":", parts.join(" "));
}
}
await show("ok", request(base + "/v1/users/u_1"));
await show("missing", request(base + "/v1/users/u_99"));
await show("invalid", request(base + "/v1/signup"));
await show("proxy", request(base + "/v1/proxy"));
await show("flaky", withRetry(() => request(base + "/v1/flaky")));
await show("limited", withRetry(() => request(base + "/v1/limited")));
await show("slow", request(base + "/v1/slow", 100));
// Nothing listens on this port any more, so fetch cannot connect at all.
const closed = http.createServer();
await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
const closedUrl = "http://127.0.0.1:" + closed.address().port;
await new Promise((resolve) => closed.close(resolve));
await show("offline", request(closedUrl + "/v1/users/u_1"));
server.close();
server.closeAllConnections();Code breakdown
- fetch throws only without a response
const kind = cause.name === "TimeoutError" ? "timeout" : "network";Only failures without a response reach this catch. A name of TimeoutError means AbortSignal.timeout expired, and everything else (refused connection, DNS) is classed as network.
- Check res.ok yourself
if (res.ok) return res.json();For 404 and 422 the fetch promise is fulfilled, so this line separates the success path. Everything else continues below to the code that reads the error body.
- Error body may not be JSON
const body = await res.json().catch(() => ({})); // an error page may not be JSONParsing the 502's <h1>Bad Gateway</h1> as JSON would throw, so .catch swaps in an empty object. The error can still be built from the status when a proxy sends something that has no code.
- Read Retry-After
retryAfterMs: retryAfter === null ? undefined : Number(retryAfter) * 1000,The Retry-After header can be a number of seconds, converted to milliseconds here. Some servers send an HTTP date instead, which you will handle in the challenge.
- What is retryable
const RETRYABLE = new Set([429, 502, 503, 504]);The list of statuses is explicit. 404 and 422 are not in it, so they are never retried.
- Backoff with full jitter
const wait = err.retryAfterMs ?? Math.random() * baseMs * 2 ** attempt;If the server gave Retry-After, that is used; otherwise the code waits a random time below a limit that doubles each attempt. The ?? operator keeps 0, so Retry-After: 0 is honoured as written.
ok: {"id":"u_1","name":"Alice"}
missing: http 404 user_not_found
invalid: http 422 validation_failed {"email":"must be a valid email address"}
proxy: http 502 (no JSON error body)
flaky: {"value":{"ok":true},"attempts":3}
limited: {"value":{"ok":true},"attempts":2}
slow: timeout
offline: network ECONNREFUSED- Send the request with a time limit
- See whether a response came or fetch threw
- Check res.ok and sort the status class
- If it is retryable, wait and try again
Got a 2xx
Parse the body and return it
A 4xx, or attempts used up
Throw a typed error so the caller can show a message
A 422 response on the wire
The shape of the error body should be the same across the whole API, so that a client can handle it with one error handler. In the exchange below the client asked to create a user with a bad email, and the server answers 422. The status line gives the class, code is for programs, message is for people, and fields is for individual form inputs.
POST /v1/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
{ "name": "Bob", "email": "bob-at-example" }
HTTP/1.1 422 Unprocessable Content
Content-Type: application/json
{ "error": { "code": "validation_failed",
"message": "One or more fields are invalid",
"fields": { "email": "must be a valid email address" } } }Which requests may be retried
When a request times out you do not know whether the server already performed it. Freely retry only methods where repeating the request leaves the same result (idempotent ones). A POST may create two records, which is why APIs such as Stripe accept an Idempotency-Key header and, for a repeated key, return the first response instead of acting again. Retry your own POST only when the docs say the server supports that header.
| Method | Idempotent? | Retry after a failure? |
|---|---|---|
| GET | Yes | Safe to retry |
| PUT / DELETE | Yes (same end result) | Safe to retry |
| PATCH | Depends on the API | Check the docs |
| POST | No | Only with an Idempotency-Key |
POST /v1/payments HTTP/1.1
Host: api.example.com
Content-Type: application/json
Idempotency-Key: 7f3a9c1e-order-1042
{ "amount": 1200, "currency": "usd" }In real projects
Error handling in real projects
Production clients do not put this logic in every component. It lives once in an HTTP client wrapper, or an SDK, and the UI only receives typed errors. The AWS SDKs retry throttling and 5xx errors by default with backoff and jitter. Some providers use 403 as well as 429 for rate limiting, so read Retry-After and the rate-limit headers as the docs describe, not only the status.
- A 422 is shown next to the form field, a 401 sends the user to log in, a 404 shows a "not found" page, and retryable errors show a "try again" button.
- Logs carry the request id, status and code, and never tokens, passwords or personal data. The message shown to users is kept apart from the operator log.
- Monitoring watches the share of 5xx responses and the number of retries; a rising retry count is often the first sign of a problem upstream.
Common mistakes
Common error-handling mistakes
Treating try/catch as complete
fetch does not throw for 404, 422 or 500, so a try/catch alone lets HTTP errors slip through. Check res.ok and read the error body.
Retrying everything, instantly, forever
A 422 will not succeed on retry, and without a delay your clients all return at the same moment, just when the server is recovering, and knock it over again. Pick the few retryable statuses and add backoff, jitter and a maximum number of attempts.
Retrying a POST without protection
When a POST times out, the server may already have created the record. Sending it again charges twice or creates two users. Without an Idempotency-Key, do not retry it.
Forgetting the timeout
fetch has no default timeout, so a server that holds the connection open and never answers leaves the promise pending indefinitely. Give every request signal: AbortSignal.timeout(ms).
Best practices
Best practices
- Keep the timeout, the res.ok check, the error-body read and the kind tag in one request function.
- Use one error shape (code, message, fields, request id) and branch on the code.
- Test the retry policy: if random and sleep are parameters you can write tests with predictable delays.
Mini challenge
Write the retry policy yourself
Write two functions. shouldRetry(method, status, hasIdempotencyKey) decides whether to retry, where a status of null means no response arrived. retryDelayMs(attempt, retryAfter, now, random) returns how many milliseconds to wait. Retry-After can be either a number of seconds or an HTTP date.
- Never retry a 4xx other than 429
- Retry null, 429, 502, 503 and 504 only for an idempotent method or when an Idempotency-Key exists
- Retry-After "3" means 3000 ms; an HTTP date means that date minus now, never below 0
- Without the header, use random() * min(5000, 100 * 2 ** attempt)
const IDEMPOTENT = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
// status is null when no response arrived (network error or timeout)
function shouldRetry(method, status, hasIdempotencyKey = false) {
// TODO: a 4xx other than 429 can never be fixed by retrying
// TODO: retry null, 429, 502, 503 and 504 only when the call is safe to repeat
}
// retryAfter is the raw Retry-After header value, or null
function retryDelayMs(attempt, retryAfter, now, random = Math.random) {
// TODO: "3" means 3000 ms
// TODO: an HTTP date means "that date minus now", never below 0
// TODO: otherwise use full jitter, capped at 5000 ms
}Expected: Ten lines print: true, false, true, false, true, 3000, 5000, 0, 400, 5000.
Show hint
Turn the HTTP date into milliseconds with Date.parse and subtract now. Check first whether the value is a plain integer. Because random is a parameter, you can pass () => 0.5 in a test and get a predictable result.
Show solution
const IDEMPOTENT = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
function shouldRetry(method, status, hasIdempotencyKey = false) {
if (status !== null && status >= 400 && status < 500 && status !== 429) return false;
const transient = status === null || [429, 502, 503, 504].includes(status);
return transient && (IDEMPOTENT.has(method) || hasIdempotencyKey);
}
function retryDelayMs(attempt, retryAfter, now, random = Math.random) {
if (retryAfter !== null) {
if (/^[0-9]+$/.test(retryAfter)) return Number(retryAfter) * 1000;
const date = Date.parse(retryAfter);
if (!Number.isNaN(date)) return Math.max(0, date - now);
}
return Math.round(random() * Math.min(5000, 100 * 2 ** attempt));
}
console.log(shouldRetry("GET", 503));
console.log(shouldRetry("POST", 503));
console.log(shouldRetry("POST", 503, true));
console.log(shouldRetry("GET", 422));
console.log(shouldRetry("DELETE", null));
console.log(retryDelayMs(1, "3", 0));
const now = Date.parse("Wed, 21 Oct 2015 07:28:00 GMT");
console.log(retryDelayMs(1, "Wed, 21 Oct 2015 07:28:05 GMT", now));
console.log(retryDelayMs(1, "Wed, 21 Oct 2015 07:27:00 GMT", now));
console.log(retryDelayMs(3, null, now, () => 0.5));
console.log(retryDelayMs(10, null, now, () => 1));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- fetch rejects only when no response arrives; 4xx and 5xx are normal responses with res.ok false.
- Read the error body in one consistent shape: branch on the code and tell 400 (not understood), 422 (bad values) and 409 (state conflict) apart.
- Retry only network errors, timeouts, 429 and 502/503/504, with exponential backoff, jitter and Retry-After, and cap the attempts.
- Never retry a non-idempotent POST without an Idempotency-Key, and give every request AbortSignal.timeout.
RFC 9110 — HTTP Semantics — IETF