PREP WITH PROOF
Menu
PROGRAMMING & APIS / PRACTICAL GUIDE

JavaScript fetch Errors: HTTP Status, JSON and Cancellation

Diagnose fetch HTTP responses, network failures, invalid JSON, consumed bodies and aborts. Includes a Node.js lab with 23 checks and 16 local HTTP requests.

THE QUICK ANSWER

fetch can resolve for an HTTP 404 because a response was received. Body reading and JSON parsing can still fail after that promise resolves. Check status explicitly, preserve the failed stage, consume the body once and keep cancellation active while reading. The local lab demonstrates these outcomes separately.

A response, a complete body and valid JSON are separate milestones

Your catch block never runs for a 404, but it does run for a successful 200 response containing broken JSON. A loading indicator disappears when headers arrive even though the body is still downloading. These symptoms are easier to diagnose when you stop treating a fetch operation as one indivisible success or failure.

Calling fetch starts an operation whose promise can resolve to a Response. That response exposes the HTTP status and headers; its arrival does not mean the body has been fully received. Reading the body is another asynchronous operation, and interpreting the resulting text as JSON is another possible failure point.

This guide uses a small JSON endpoint policy and a reproducible Node.js HTTP fixture. The objective is to preserve the stage at which an operation failed, so a UI or caller can make a useful decision. It is not a universal API client, retry framework or test of browser CORS behavior.

Observed resultWhat happenedUseful next check
Response with status 404HTTP response reached the callerInspect status and endpoint contract
Fetch promise rejectsNo usable Response returned to this callCheck cancellation, request setup and transport evidence
Headers received, body read rejectsResponse started but body could not be consumedCheck abort, interrupted connection and decoding
Body text is not valid JSONTransport produced text that cannot be parsedInspect content type and invented response fixture
JSON parses but fields are wrongSyntax succeeded; application contract failedValidate required data shape separately

Source: WHATWG Fetch Standard: response and body processing ↗

Why fetch does not throw for HTTP 404 or 500

A normal HTTP error response is still a response. The lab deliberately returns a 404 with valid JSON and confirms that fetch resolves. Its Response has status 404 and ok false, and its JSON body can still be read. The status is not converted into a rejected promise automatically.

Check the response before treating it as endpoint success. Response.ok covers the 200–299 range. Your application can use that broad rule or a narrower documented contract, but the decision must be explicit. A 201 response might be valid for one operation, while another endpoint promises a particular status and body shape.

An HTTP failure branch should preserve the status rather than turning every failure into “network error.” A 429 response, a 404 response and an interrupted connection suggest different investigations. Do not infer that any of them is safe to retry without considering the method, operation semantics and server guidance.

The example helper returns a tagged http outcome and cancels the unread response body. It intentionally discards error details to keep the policy small. A real API may require a bounded error payload or request identifier; design that separately, and avoid logging credentials or a complete sensitive response body.

Source: MDN: using fetch, status checks and cancellation ↗

Keep body consumption and parsing errors visible

The listing reads successful JSON responses as text, then calls JSON.parse in a separate try block. That separation is an instructional choice: a failed text read becomes body-read, while completed text with invalid JSON becomes invalid-json. Calling response.json directly combines the read and parse into one returned promise.

The malformed endpoint returns HTTP 200 and application/json but sends {broken. The raw response is ok, yet json rejects with SyntaxError. That is evidence about response syntax, not a DNS or connectivity failure. A server can also return an HTML error page with status 200; our helper rejects its media type before attempting JSON parsing.

This helper accepts only application/json after stripping media-type parameters and normalizing case. That narrow choice matches its invented endpoint contract. It does not accept every JSON-related media type, and a content-type header alone is not proof of valid JSON. If your API uses application/problem+json, extend the policy deliberately and test it.

A 204 response has no JSON document to parse. The helper explicitly maps it to null as a successful empty result. That is an application convention, not a promise that all empty responses mean null. A 200 response with empty text should fail this JSON policy unless your endpoint specifies another result.

Response bodies are generally consumed once. The fixture reads one response with json, observes bodyUsed, then confirms a second text read rejects. If you need diagnostic text and parsed JSON, reading once and parsing that text avoids the accidental second read. Cloning or buffering large bodies has its own resource cost.

Source: MDN: Response.json errors and body consumption ↗

A deadline must cover the body read too

The helper combines the caller’s signal with a deadline signal. It passes that combined signal to fetch and continues reading the body under the same operation. Clearing a custom timeout immediately after fetch resolves would leave the body-read stage outside that timeout, which can explain requests that appear to hang after their status is visible.

The raw cancellation fixture waits for fetch to return a Response from an endpoint that has sent headers and a partial body. It then aborts the controller and confirms that json rejects with AbortError. The already-delivered status was real; cancellation prevented completion of the body consumption.

A separate endpoint never sends a response. The caller-cancellation check waits until the server has observed the request before aborting. Another check uses a deadline. These cases exercise rejection before a usable response is returned, while the partial-body case exercises cancellation after a Response exists.

AbortSignal.any uses the reason from the signal that caused the combined signal to abort. Our helper labels a reason named TimeoutError as timeout and other abort reasons as cancelled. That is a display convention for these fixtures, not a universal forensic classification. Applications passing custom abort reasons should preserve those reasons appropriately.

Aborting the client does not prove that a server-side action was rolled back. A server may have accepted a write before the caller stopped waiting. This lab uses GET requests with invented data and does not test transactional cancellation. Treat cancellation and retry safety as separate decisions.

Source: Node.js: fetch, AbortSignal timeout and signal composition ↗

Run a local HTTP fixture with explicit outcomes

Save the following as fetch_lab.mjs and run node fetch_lab.mjs with a compatible modern Node.js runtime. We executed it on Node.js 24.22.1. It uses built-in modules and binds an ephemeral port on the IPv4 loopback interface; it does not call an external API or require third-party packages.

getJsonResult appears first so you can inspect the stage boundaries independently of the server fixture. It assumes a trusted URL and valid timeout options. The later server routes deliberately create malformed data, empty responses, connection failure and incomplete bodies. The finally block destroys held responses and closes the test server.

The helper reads a complete response into memory before parsing. A time limit is not a byte limit, and a successful parse is not schema validation. Before using this pattern with untrusted large responses, add a bounded streaming/body policy and validate the data structure required by your application. CPU-bound JSON parsing is not preempted by an abort signal.

import assert from 'node:assert/strict';
import {createServer} from 'node:http';
import {once} from 'node:events';

// Small JSON endpoint policy, not a general HTTP client.
async function getJsonResult(url, {signal, timeoutMs = 2000} = {}) {
  const deadline = AbortSignal.timeout(timeoutMs);
  const active = signal ? AbortSignal.any([signal, deadline]) : deadline;
  const aborted = () => ({kind: active.reason?.name === 'TimeoutError' ? 'timeout' : 'cancelled'});
  let response;
  try {
    response = await fetch(url, {signal: active});
  } catch (error) {
    return active.aborted ? aborted() : {kind: 'fetch-failure', name: error.name};
  }
  if (!response.ok) {
    try { await response.body?.cancel(); } catch {}
    return {kind: 'http', status: response.status};
  }
  // This endpoint contract treats 204 as a successful empty result.
  if (response.status === 204) return {kind: 'ok', data: null};
  const media = (response.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
  if (media !== 'application/json') {
    try { await response.body?.cancel(); } catch {}
    return {kind: 'unexpected-media', media};
  }
  let text;
  try { text = await response.text(); }
  catch (error) { return active.aborted ? aborted() : {kind: 'body-read', name: error.name}; }
  try { return {kind: 'ok', data: JSON.parse(text)}; }
  catch { return {kind: 'invalid-json'}; }
}

let requests = 0, checks = 0;
const held = new Map();
const waiting = new Map();
function seen(path, response) {
  held.set(path, response);
  waiting.get(path)?.();
}
function waitSeen(path) {
  return held.has(path) ? Promise.resolve() : new Promise(resolve => waiting.set(path, resolve));
}
const server = createServer((request, response) => {
  requests++;
  const path = new URL(request.url, 'http://localhost').pathname;
  if (path.startsWith('/never')) { seen(path, response); return; }
  if (path === '/disconnect') { request.socket.destroy(); return; }
  if (path.startsWith('/held-body')) {
    response.writeHead(200, {'content-type': 'application/json'});
    response.flushHeaders(); response.write('{'); seen(path, response); return;
  }
  if (path === '/empty') { response.writeHead(204); response.end(); return; }
  const status = path.startsWith('/status/') ? Number(path.split('/').at(-1)) : 200;
  const media = path === '/html' ? 'text/html' : 'application/json; charset=utf-8';
  response.writeHead(status, {'content-type': media});
  response.end(path === '/bad' ? '{broken' : path === '/html' ? '<h1>Error</h1>' : '{"value":7}');
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const origin = `http://127.0.0.1:${server.address().port}`;
function check(value, label) { assert.ok(value, label); checks++; }
try {
  const raw404 = await fetch(origin + '/status/404');
  check(raw404.status === 404 && !raw404.ok, '404 resolves to Response');
  check((await raw404.json()).value === 7, 'error response can have valid JSON');
  const rawBad = await fetch(origin + '/bad');
  check(rawBad.ok, 'malformed JSON can have successful HTTP status');
  await assert.rejects(rawBad.json(), SyntaxError); checks++;
  const used = await fetch(origin + '/status/200');
  check((await used.json()).value === 7, 'first body consumption succeeds');
  check(used.bodyUsed, 'body marked consumed');
  await assert.rejects(used.text(), TypeError); checks++;
  check((await getJsonResult(origin + '/status/200')).data.value === 7, 'valid JSON');
  check((await getJsonResult(origin + '/status/201')).kind === 'ok', '201 accepted');
  for (const status of [404, 429, 500]) {
    const result = await getJsonResult(origin + '/status/' + status);
    check(result.kind === 'http' && result.status === status, 'HTTP policy ' + status);
  }
  check((await getJsonResult(origin + '/empty')).data === null, '204 explicit empty policy');
  check((await getJsonResult(origin + '/bad')).kind === 'invalid-json', 'JSON parsing separate');
  check((await getJsonResult(origin + '/html')).kind === 'unexpected-media', 'HTML rejected by contract');
  const failed = await getJsonResult(origin + '/disconnect');
  check(failed.kind === 'fetch-failure' && failed.name === 'TypeError', 'connection failure before response');
  const controller = new AbortController();
  const pending = getJsonResult(origin + '/never-cancel', {signal: controller.signal});
  await waitSeen('/never-cancel'); controller.abort();
  check((await pending).kind === 'cancelled', 'caller abort');
  const timeout = await getJsonResult(origin + '/never-timeout', {timeoutMs: 100});
  check(timeout.kind === 'timeout', 'deadline abort');
  const pre = new AbortController(); pre.abort();
  check((await getJsonResult(origin + '/unused', {signal: pre.signal})).kind === 'cancelled', 'already aborted signal');
  const bodyController = new AbortController();
  const bodyResponse = await fetch(origin + '/held-body-abort', {signal: bodyController.signal});
  check(bodyResponse.ok, 'headers arrive before complete body');
  bodyController.abort();
  await assert.rejects(bodyResponse.json(), {name: 'AbortError'}); checks++;
  const interrupted = await fetch(origin + '/held-body-error');
  check(interrupted.ok, 'second response headers arrive');
  const read = interrupted.text(); held.get('/held-body-error').destroy();
  await assert.rejects(read, TypeError); checks++;
  console.log(`PASS: ${checks} checks; ${requests} local HTTP requests; ${process.version}`);
} finally {
  for (const response of held.values()) response.destroy();
  server.closeAllConnections();
  await new Promise(resolve => server.close(resolve));
}

What the executed checks establish

The exact listing passed 23 checks across 16 local HTTP requests on Node.js 24.22.1. It checks raw fetch behavior alongside the helper, so a successful wrapper outcome is not the only evidence. The 404 body is valid JSON, and the broken JSON response is HTTP-successful; those deliberately crossed cases expose the difference between the stages.

The helper checks cover valid 200 and 201 results, 404/429/500 status outcomes, the explicit 204-to-null convention, unexpected HTML, invalid JSON, a connection destroyed before a response, caller cancellation, a deadline and an already-aborted signal. The final raw checks distinguish aborting an incomplete body from a connection interruption while reading it.

The already-aborted case does not need to send another request. The request count is measured by the fixture server, while the check count includes assertions about response properties and rejected reads. Neither number is a performance measurement or a claim of exhaustive coverage.

These are Node loopback results. They do not test browser CORS, service workers, TLS failures, DNS errors or a real upstream proxy. In a browser, several fetch failures can have limited JavaScript-visible detail. A TypeError alone does not establish a specific root cause; combine application evidence with the browser’s network and security diagnostics.

Report the failed stage before choosing a remedy

For HTTP outcomes, record the status, the operation and a safe request identifier if available. For body failures, distinguish an abort from interrupted consumption. For parse failures, reproduce the smallest invented response that violates the endpoint contract. For valid JSON with missing fields, report a schema or application-data problem rather than calling the transport unreliable.

Keep loading state active until the operation your UI promised is complete. If the UI promises parsed data, receipt of response headers is too early to declare success. Likewise, show a deliberate cancellation differently from an unexpected failure when that distinction helps the user understand what happened.

The practical sequence is short: obtain the response, apply the status and media policy, consume the body once, parse the text, then validate application data. Preserve cancellation through the asynchronous stages. That sequence makes a catch block useful because it no longer has to guess which kind of success the application expected.

KEEP THESE THREE THINGS

Your next steps

  1. Separate response receipt, HTTP policy, body reading, JSON parsing and data validation.
  2. Keep a deadline or caller cancellation attached through body consumption.
  3. Use status and stage-specific evidence; a generic TypeError does not identify the root cause.

Sources & official resources

Linked resources checked on 2026-10-31. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →