Fetch Errors
When requests fail.
Requests fail. The server might be down, or the page might not exist. There's a catch here that trips up many beginners. Fetch only rejects when the network itself fails. A four oh four is still a successful response, so you have to check it yourself.

- Requests fail
- Server down, page missing
- 404 doesn't reject!
Check response.ok
Our server returns four oh four for anything except slash users. Get JSON checks response dot o k, and throws an error if it's false. The first call succeeds. The second gets a four oh four, and we catch our own error. Run it.
import http from "node:http";
const server = http.createServer((req, res) => {
if (req.url !== "/users") { res.statusCode = 404; return res.end(); }
res.end(JSON.stringify(["Ana", "Ben"]));
}).listen(3001);
async function getJSON(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`Request failed with ${res.status}`);
return res.json();
}
for (const path of ["/users", "/missing"]) {
try { console.log(await getJSON("http://localhost:3001" + path)); }
catch (err) { console.log("Error:", err.message); }
}
server.close();[ 'Ana', 'Ben' ] Error: Request failed with 404
A safe pattern
Wrap fetch in a small helper like get JSON. Check response dot o k, throw a clear error, and catch it where you can show a message to the user. Network errors and bad status codes then end up in the same catch block.
| key | value |
|---|---|
| Network down | fetch rejects |
| 404, 500 | fetch resolves! |
| Check res.ok | throw yourself |
| One helper | used everywhere |
Summary
Fetch doesn't reject on a four oh four, so always check response dot o k, and throw your own error. Next, practice with an async countdown.
Key takeaways- fetch resolves on 404
- if (!res.ok) throw
- try / catch