Sub topic 4
Handling Errors Correctly: Why fetch Resolves on 404
This chapter assumes you know Promises, async/await, and try/catch. It also assumes you know the Response properties status, ok, and statusText from the earlier chapter on inspecting the response.
New fetch users often expect a 404 or 500 to land in their catch block. It does not. The Promise from fetch() rejects only when the request could not complete. If the server sent back any HTTP response, even an error page, the Promise resolves.
Two kinds of failure
From fetch's point of view, a 404 is a success. The request went out, the server answered, and you received a Response. Whether that answer is the one you wanted is for your code to decide.
| Situation | What fetch does | What you see |
|---|---|---|
| Server returns 200 | Resolves | `response.ok === true` |
| Server returns 404, 401, or 500 | Resolves | `response.ok === false`, `response.status` set |
| DNS lookup fails or the device is offline | Rejects | `TypeError` |
| Browser blocks the response under CORS | Rejects | `TypeError` (details only in the console) |
| Request is aborted | Rejects | `DOMException` named `AbortError` |
response.ok is true only for statuses from 200 to 299. Anything else, including redirects that were not followed, gives false.
Check `ok` before reading the body
The fix is to check response.ok yourself and throw when it is false. Then both kinds of failure arrive at the same catch.
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));If you skip the check, a 500 response with an HTML error page goes straight to response.json(). That throws a SyntaxError such as "Unexpected token '<'", and the message hides the real problem.
Telling the failures apart
You often need to react differently to each failure. A 404 might mean showing "user not found". A network error might mean showing "you appear to be offline". A custom error class that carries the status makes this easy.
class HttpStatusError extends Error {
constructor(response) {
super(`HTTP ${response.status} ${response.statusText}`);
this.name = 'HttpStatusError';
this.status = response.status;
}
}
async function getUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) throw new HttpStatusError(response);
return response.json();
}
async function showUser(id) {
try {
const user = await getUser(id);
console.log('Loaded', user);
} catch (err) {
if (err instanceof HttpStatusError && err.status === 404) {
console.log('No such user.');
} else if (err instanceof HttpStatusError) {
console.log(`Server problem (${err.status}). Try again later.`);
} else if (err.name === 'TypeError') {
console.log('Network error: check your connection.');
} else {
throw err;
}
}
}
showUser(42);Three details matter here:
- A
TypeErrorfrom fetch is deliberately vague. The browser hides CORS failure details from scripts, so open the console and network panel to find the cause. - A bug in your own code, such as calling a method on
undefined, also throwsTypeError. Keep thetryblock small so you don't report your own bugs as network errors. - Rethrow errors you don't recognize. Swallowing them makes debugging much harder.
Reading the error body
Many APIs send a JSON explanation with an error status, such as {"error": "email already taken"}. The body is still readable when ok is false. Read it before you throw so the message reaches the user.
async function createAccount(data) {
const response = await fetch('https://api.example.com/accounts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (!response.ok) {
const text = await response.text();
let detail = text;
try {
detail = JSON.parse(text).error ?? text;
} catch {
// Body was not JSON; keep the raw text.
}
throw new Error(`HTTP ${response.status}: ${detail}`);
}
return response.json();
}Reading with text() first and then parsing protects you from servers that return JSON on some errors and HTML on others.
Exercise
A request to a working server returns status 503, and the code calls await response.json() with no ok check. The 503 body is an HTML page. What error appears, and why didn't fetch itself reject?
Show answer
response.json() throws a SyntaxError because HTML is not valid JSON. Fetch didn't reject because the server sent a complete HTTP response. Fetch rejects only when no response arrives, for example from a network failure, a CORS block, or an abort.
Exercise
Write the condition that sends a 204 No Content response down the success path and a 302 that was not followed down the error path.
Show answer
if (!response.ok) throw .... ok is true for any status from 200 to 299, so 204 passes and 302 fails. Note that a 204 has no body, so don't call response.json() on it.