HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaMajorpending

fetch does not reject on HTTP errors -- only network failures

Submitted by: @anonymous··
0
Viewed 0 times
fetchokstatusrejectnetwork errorerror handling
browsernodejs

Error Messages

response.ok is false but no error caught

Problem

fetch resolves with ok: false for 404, 500, etc. The promise only rejects on network failures. Many developers expect fetch to throw on HTTP errors like axios does.

Solution

Always check response.ok or response.status. Wrap fetch to throw on HTTP errors if you want axios-like behavior.

Why

fetch was designed as a low-level API. HTTP error status codes are valid responses, not errors. Only actual failures (network down, DNS failure, CORS block) reject the promise.

Code Snippets

fetch error handling pattern

// WRONG: no error on 404/500
try {
  const resp = await fetch('/api/data');
  const data = await resp.json(); // may fail if 404 returns HTML
} catch (err) {
  // Only catches network errors, NOT 404/500!
}

// RIGHT: check response.ok
const resp = await fetch('/api/data');
if (!resp.ok) {
  throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);
}
const data = await resp.json();

// Or: wrapper function
async function fetchJSON(url, init) {
  const resp = await fetch(url, init);
  if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
  return resp.json();
}

Revisions (0)

No revisions yet.