Why doesn't fetch fail on a 404?
How "the server answered with an error" differs from "there's no answer at all", and why you check res.ok.
try...catch to catch every error. The server answered "404, no such fish" — and catch stayed silent, while the screen proudly said "undefined: undefined kg". Is fetch broken? No. I just didn't understand what it promises.The fetch promise promises one thing: the response will be delivered. Not "the response will be good", but "we got through and heard something". 404 and 500 are complete HTTP responses: the server received the request, thought about it and answered. So the promise fulfills — with res.ok === false.
try {
const res = await fetch("/api/stock");
console.log("Got a response:", res.status, "ok:", res.ok);
console.log(await res.json());
} catch (error) {
console.log("catch:", error.message);
}500 — and catch didn't fire: as far as fetch is concerned, all went well.The promise rejects only when there's no response at all: the internet is down, the server doesn't exist, the browser blocked the request under its security rules. Then fetch throws a TypeError.
try {
await fetch("/api/stock");
console.log("This line won't be printed");
} catch (error) {
console.log(error.name + ": " + error.message);
}Why was it designed this way? Because fetch doesn't know what counts as an error for you:
- a
404can be the expected answer: "is the usernamebytefree?" → "no such user" — great news; - in the body of a
400the server often explains what's wrong: "the email field is empty" — you need to read it and show it; - a
401is a reason to send the user to the login page, not to show "something broke".
So the decision was left to you. For convenience there's res.ok: it's true for any status 200–299.
async function getJSON(url) {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return res.json();
}
try {
const fish = await getJSON("/api/fish");
console.log("Fish in stock:", fish.length);
await getJSON("/api/fish/999");
} catch (error) {
console.log("Error:", error.message);
}catch catches everything again.fetch is honest: it reports on delivery, not on the quality of the news. Bad news from the server is still news. Reading it is my job. As is begging for fish.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.