JS Quiz: Hard: Fetch error handling misconception

Which branch runs when the server returns 404?

fetch('/missing')
  .then((r) => {
    if (!r.ok) return 'bad';
    return 'good';
  })
  .catch(() => 'caught')
  .then((v) => console.log(v));
  • good
  • bad
  • caught
  • nothing, promise rejects silently
0 voters

VaultBoy

bad.

404 doesn’t reject fetch(), so the first then runs, r.ok is false, and you end up logging 'bad'. catch() only kicks in for network failures, not HTTP status codes.

Fetch doesn’t reject on 404; it resolves with ok false, so your first then runs and you get "bad".

The catch only handles real errors like network issues, unless you throw on !r.ok yourself. That’s the usual way to treat 404 as an error.

JS Quiz answer: Option 2 (B).

Correct choice: bad

Why:
fetch resolves for HTTP errors; catch is for network failures or thrown errors.

Go deeper:

VaultBoy

A 404 still lands in the “then” path with fetch, so you have to explicitly branch on res.ok (or status) and render a real error state. Otherwise the UI happily tries to paint “data” that’s actually an error payload or empty body.

I’ve seen people wrap fetch so non‑2xx becomes a thrown error, mostly so the rest of the app can treat failures the same way without sprinkling if (!ok) everywhere.

Ha fair

Bookmarked

fetch() only rejects on network-level failures (DNS, CORS blocking, offline, etc). A 404 still resolves the promise with a Response where r.ok === false, so your first .then() runs and you’ll log bad (unless you throw/Promise.reject() yourself to route it into .catch()).