Sub topic 4
Handling Errors Correctly: Why fetch Resolves on 404
This chapter assumes you can already make a GET request with fetch(), inspect response.status and response.ok, and read a body with json() or text(). It also assumes you are comfortable with async/await, try/catch, and the meaning of common HTTP status codes such as 200, 404, and 500.
The most common fetch bug is assuming that a failed request lands in your catch block. A request that comes back with 404 or 500 does not reject the Promise. This chapter explains why fetch behaves this way, sorts the ways a request can fail into clear categories, and shows code that handles each category on purpose.
The Working Model: Two Separate Questions
Every fetch call answers two separate questions:
- Did an HTTP exchange happen? The browser either received a response from a server or it did not.
- Did the server say the request succeeded? If a response arrived, its status code tells you whether the server accepted the request.
The Promise returned by fetch() only answers the first question. If the browser got any HTTP response back, including 404 Not Found or 500 Internal Server Error, the Promise resolves with a Response object. The Promise rejects only when no usable response was received.
This design is deliberate. From the network layer's point of view, a 404 is a successful exchange. The server understood the request and replied. Whether a 404 is an error depends on the application. Some code treats a 404 as "this user has no profile yet," which is a normal case. Fetch leaves that decision to you.
What Actually Makes fetch Reject
The fetch() Promise rejects in a small set of situations. Knowing them lets you write precise error messages.
| Cause | Error type | Has a Response? | Typical fix |
|---|---|---|---|
| Server unreachable, DNS failure, offline | `TypeError` | No | Retry, show "check your connection" |
| CORS policy blocked the response | `TypeError` | No | Fix server CORS headers |
| Malformed URL or invalid request options | `TypeError` | No | Fix the calling code |
| `redirect: 'error'` and the server redirected | `TypeError` | No | Handle the redirect or change the option |
| Request cancelled through an `AbortSignal` | `DOMException` named `AbortError` | No | Usually ignore silently |
| Timeout through `AbortSignal.timeout()` | `DOMException` named `TimeoutError` | No | Retry or report a timeout |
| Server replied 4xx or 5xx | No rejection | Yes | Check `response.ok` and throw |
| Body is not valid JSON | `SyntaxError` from `json()` | Yes | Check content type, read as text |
The TypeError cases have a weakness: browsers deliberately make them look the same. A CORS block, a DNS failure, and a refused connection all produce a generic message. Chrome says Failed to fetch, Firefox says NetworkError when attempting to fetch resource., and Safari says Load failed. Browsers hide the details on purpose, so that a script cannot probe which hosts exist on a private network. Do not parse these message strings. Use the browser's developer tools console and network panel to find out which case you hit during development.
Cancellation and timeouts are covered fully in a later chapter. For now, recognize them by err.name and keep them apart from real network failures.
The Classic Bug
Here is code that looks correct but is not:
fetch('https://api.example.com/users/9999')
.then((response) => response.json())
.then((user) => console.log('Loaded user:', user.name))
.catch((err) => console.error('Request failed:', err.message));Suppose user 9999 does not exist and the server replies with a 404. Depending on the server, one of three things happens:
- The server returns a JSON error body such as
{"error":"not found"}. The code logsLoaded user: undefined, and nothing reports an error. - The server returns an HTML error page.
response.json()rejects with aSyntaxErrorlikeUnexpected token '<', "<!DOCTYPE "... is not valid JSON. Thecatchblock runs, but the message hides the real problem, which is the 404. - The server returns an empty body.
json()rejects withUnexpected end of JSON input.
None of these outcomes tell you "404 Not Found." If you see Unexpected token '<' in a fetch-related error, the first thing to check is whether the request returned an error status with an HTML body.
Checking response.ok
The fix is to check the status before parsing. response.ok is true when the status is between 200 and 299 inclusive, and false otherwise.
async function getUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText}`);
}
return response.json();
}
getUser(1)
.then((user) => console.log(user))
.catch((err) => console.error('Request failed:', err.message));Now one catch block receives both kinds of failure: rejections from fetch itself and the error you throw for bad statuses.
Avoid writing if (response.status !== 200). It wrongly treats 201 Created and 204 No Content as failures. Use response.ok, or compare specific status codes only when you need to handle one of them differently.
Keeping the Server's Error Details
Many APIs send useful information with an error status, such as {"error":"email already registered"}. A plain Error with only the status code discards it. A small custom error class keeps the status and the body together so callers can make decisions:
class HttpError extends Error {
constructor(response, body) {
super(`HTTP ${response.status} ${response.statusText}`.trim());
this.name = 'HttpError';
this.status = response.status;
this.body = body;
}
}
async function readErrorBody(response) {
const text = await response.text();
try {
return JSON.parse(text);
} catch {
return text;
}
}
async function getJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new HttpError(response, await readErrorBody(response));
}
return response.json();
}
try {
const user = await getJson('https://api.example.com/users/9999');
console.log(user);
} catch (err) {
if (err instanceof HttpError && err.status === 404) {
console.log('No such user');
} else if (err instanceof HttpError) {
console.error(`Server error ${err.status}:`, err.body);
} else {
console.error('Network or parsing problem:', err.message);
}
}readErrorBody reads the body as text first and then tries to parse it. This is safer than calling json() directly, because error bodies are often HTML or plain text even when successful responses are JSON. Since a body can be read only once, reading it as text and then parsing that string avoids trying to read it twice.
The final chapter of this tutorial builds a full wrapper around this idea. Here the point is that a status error should carry enough data for the caller to act on.
Classifying Every Failure in One Place
When you need different behavior for each kind of failure, separate the steps. Each try block then covers exactly one source of errors:
async function loadJson(url, options = {}) {
let response;
try {
response = await fetch(url, options);
} catch (err) {
if (err.name === 'AbortError' || err.name === 'TimeoutError') throw err;
throw new Error(`Network error requesting ${url}`, { cause: err });
}
if (!response.ok) {
throw new Error(`HTTP ${response.status} from ${url}`);
}
if (response.status === 204) return null;
try {
return await response.json();
} catch (err) {
throw new Error(`Invalid JSON from ${url}`, { cause: err });
}
}Several details here are easy to get wrong:
return awaitinsidetry. Writingreturn response.json()withoutawaitreturns the pending Promise immediately. If it rejects later, the localcatchnever sees it. Theawaitkeeps the rejection inside thetryblock.- 204 No Content. A 204 response has an empty body, so calling
json()on it throwsSyntaxError. Check for it explicitly. { cause: err }. Thecauseoption onErrorpreserves the original error, so the stack trace and Node's detailed network reason survive when you wrap the error with a clearer message.- Aborts pass through unchanged. A cancelled request is usually something your own code asked for, so it should not be reported as a network failure.
Edge Cases That Do Not Look Like Errors
Some responses resolve, have a confusing status, and need special attention.
Redirects are followed silently. By default fetch follows 301, 302, 307, and 308 redirects. The Response you get is the final one. response.redirected is true and response.url shows where you ended up. A common surprise is an expired session: the API redirects to a login page, fetch follows the redirect, and you receive 200 OK with an HTML body. response.ok is true, but json() fails. Checking response.redirected or the Content-Type header catches this case.
Opaque responses have status 0. With mode: 'no-cors', a cross-origin response is opaque: response.type is 'opaque', status is 0, ok is false, and the body cannot be read. The request may have succeeded on the server, but your code cannot know. Do not use no-cors to "fix" a CORS error when you need the data. The CORS chapter explains the real fix.
Error statuses are not always failures. A 404 from a "check if username exists" endpoint may be the answer you want. A 409 Conflict may mean "already done." Handle these statuses before the generic !response.ok check:
async function usernameTaken(name) {
const response = await fetch(`https://api.example.com/users/by-name/${encodeURIComponent(name)}`);
if (response.status === 404) return false;
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return true;
}Deciding What to Retry
Once failures are classified, retry decisions follow from them:
| Failure | Retry? | Reason |
|---|---|---|
| Network `TypeError` | Yes, with backoff | Often temporary: flaky Wi-Fi, server restart |
| `TimeoutError` | Yes, a limited number of times | Server may be briefly overloaded |
| `AbortError` | No | Your code cancelled it |
| 408, 429, 502, 503, 504 | Yes, with backoff | Server says try later; honor `Retry-After` on 429 and 503 |
| 500 | Sometimes | Only if the request is safe to repeat |
| Other 4xx | No | The request itself is wrong; repeating it gives the same answer |
| `SyntaxError` on parse | No | The response format is wrong |
Only retry non-idempotent requests, such as most POSTs, when you know the server will not apply them twice. A network error after sending a POST does not tell you whether the server processed it.
const RETRYABLE = new Set([408, 429, 502, 503, 504]);
async function fetchWithRetry(url, options = {}, attempts = 3) {
for (let attempt = 1; ; attempt++) {
try {
const response = await fetch(url, options);
if (response.ok || !RETRYABLE.has(response.status) || attempt === attempts) {
return response;
}
} catch (err) {
if (err.name === 'AbortError' || attempt === attempts) throw err;
}
await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 250));
}
}
const response = await fetchWithRetry('https://api.example.com/status');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(await response.json());fetchWithRetry returns the last Response even when it is an error status. The caller still owns the response.ok check, which keeps the function focused on one job.
Summary
fetch()rejects only when no response arrives: network failure, CORS block, invalid request, or abort.- Any HTTP status, including 404 and 500, resolves the Promise. Check
response.okyourself. - Parsing can fail separately with a
SyntaxError. AnUnexpected token '<'message usually points to an unchecked error status returning HTML. - Keep the status and error body in a custom error so callers can respond to specific cases.
- Classify failures before deciding to retry. Retry transient network and server errors, never aborts or ordinary 4xx responses.
Exercise
A teammate's code runs fetch('/api/orders').then(r => r.json()).then(render).catch(showError). When the session expires, users see a blank page and the console shows "SyntaxError: Unexpected token '<'". The network panel shows a 302 followed by a 200 for /login. Explain what is happening and name two checks that would catch it.
Show answer
Fetch followed the 302 redirect to the login page automatically, so the final Response has status 200 and ok is true, but its body is HTML. Calling json() on HTML throws the SyntaxError, and the generic handler hides the cause. Checking response.redirected (or that response.url still points at the API) and checking that the Content-Type header includes application/json before parsing would both catch it. A response.ok check alone would not, because the final status is 200.
Exercise
In the function below, a server returns 200 with a malformed JSON body. Which catch block handles the error, and why? async function f(url) { try { const r = await fetch(url); if (!r.ok) throw new Error('bad status'); return r.json(); } catch (e) { console.log('inner'); throw e; } } f(url).catch(() => console.log('outer'));
Show answer
Only "outer" is logged. Because the function uses return r.json() without await, it returns the pending Promise and leaves the try block before the parse fails. The rejection happens outside the try, so the inner catch never runs. Writing return await r.json() would make "inner" log first, followed by "outer".
Exercise
For each failure, say whether a retry loop should retry it: (a) TypeError "Failed to fetch" on a GET, (b) a 401 Unauthorized, (c) a 503 with Retry-After: 5, (d) an AbortError from the user closing a dialog, (e) a network TypeError after sending a POST that charges a credit card.
Show answer
(a) Yes, with backoff, because it is likely a transient network problem and GET is safe to repeat. (b) No, because repeating the request with the same credentials gives the same answer, so the code should refresh the credentials or ask the user to log in. (c) Yes, after waiting about 5 seconds as the header asks. (d) No, because the cancellation was intentional. (e) Not automatically, because the server may have charged the card before the connection dropped. Retry only if the API supports an idempotency key, or check the payment status first.