AI Hints
Home›JavaScript Tutorial›Promise.all and fetch
JavaScript · Lesson 87 of 138

Fetch Errors

When requests fail.

⏱ 2 min read▶ Video at 1:44:50🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Fetch Errors
From the video: Fetch Errors
  • 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.

app.mjsjavascript
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();
Output
[ '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.

keyvalue
Network downfetch rejects
404, 500fetch resolves!
Check res.okthrow yourself
One helperused 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
Next up: Practice: Async Countdown — putting it together