Skip to content

Software / Practical guide

JavaScript fetch: why an HTTP 404 does not automatically trigger catch

Receiving an HTTP response is only the first step. A runnable example distinguishes status errors, unreadable JSON and data the application cannot use.

An API returns HTTP 404. The call is inside a try block, yet the code after await fetch(url) still runs. Why does the error not automatically reach catch here?

Because fetch() distinguishes a failed request from an HTTP response that was received. An error response can arrive successfully. As MDN documents, a status such as 404 does not by itself reject the promise. An invalid address or network failure can. The application must check the HTTP status. MDN: fetch()

A useful API call therefore needs several checks. A single catch cannot replace them.

Four questions to ask about a response

For a small application that loads a title, I would ask the following questions.

Review What it tells us in this example
Did await fetch(url) return a response? The code can examine a Response object.
Is antwort.ok true? The status is in the range 200–299.
Can await antwort.json() read and parse the body? The response body can be parsed as JSON.
Is daten.titel a non-empty string? The data has the shape the display requires.

ok checks only the range of status codes. It establishes neither the content nor whether a business operation has completed. See the Response.ok documentation for its definition.

Likewise, json() does not check a schema. Valid JSON can represent an object, an array, a number or null as its value. Reading the body can still fail after fetch() has returned a response. MDN describes abort, read and syntax errors among the possible causes. MDN: Response.json()

A small server that deliberately returns bad responses

This example simulates an API that returns a title. Its HTTP server listens only on 127.0.0.1, uses an automatically assigned port and shuts down at the end. All responses use artificial test data, and all requests stay on the local machine.

Save it as fetch-pruefung.mjs and run it with node fetch-pruefung.mjs to run it. It needs no additional packages and was tested with Node.js 22.23.1 on macOS. Starting and closing the server uses the built-in Node.js HTTP API.

import { createServer } from "node:http";

async function titelLaden(url) {
  const antwort = await fetch(url);
  if (!antwort.ok) {
    try {
      await antwort.body?.cancel();
    } catch {
      // Ein Fehler beim Aufräumen ersetzt nicht den HTTP-Status.
    }
    throw new Error(`HTTP ${antwort.status}`);
  }

  let daten;
  try {
    daten = await antwort.json();
  } catch (ursache) {
    throw new Error("Antwort nicht als JSON lesbar", { cause: ursache });
  }
  if (
    daten === null || typeof daten !== "object" ||
    Array.isArray(daten) || typeof daten.titel !== "string" ||
    daten.titel.trim() === ""
  ) {
    throw new Error("Titel fehlt oder ist ungültig");
  }
  return daten.titel.trim();
}

const faelle = new Map([
  ["/gut", [200, '{"titel":"Werkstatt"}']],
  ["/fehlt", [404, '{"fehler":"Nicht gefunden"}']],
  ["/dienst", [503, '{"fehler":"Nicht verfügbar"}']],
  ["/kaputt", [200, '{"titel":']],
  ["/form", [200, '{"titel":42}']],
  ["/leer", [204, ""]],
]);

const server = createServer((anfrage, antwort) => {
  const [status, inhalt] = faelle.get(anfrage.url) ?? faelle.get("/fehlt");
  antwort.writeHead(status, { "Content-Type": "application/json" });
  antwort.end(inhalt);
});
await new Promise((resolve, reject) => {
  server.once("error", reject);
  server.listen(0, "127.0.0.1", resolve);
});

try {
  const basis = `http://127.0.0.1:${server.address().port}`;
  const probe = await fetch(basis + "/fehlt");
  console.log(`Ohne Statusprüfung: ${probe.status}, ok=${probe.ok}`);
  await probe.text();

  for (const pfad of faelle.keys()) {
    try {
      console.log(pfad + ": " + await titelLaden(basis + pfad));
    } catch (fehler) {
      console.log(pfad + ": " + fehler.message);
    }
  }
} finally {
  await new Promise((resolve, reject) => {
    server.close(fehler => fehler ? reject(fehler) : resolve());
  });
}

Expected output

Ohne Statusprüfung: 404, ok=false
/gut: Werkstatt
/fehlt: HTTP 404
/dienst: HTTP 503
/kaputt: Antwort nicht als JSON lesbar
/form: Titel fehlt oder ist ungültig
/leer: Antwort nicht als JSON lesbar

The first line illustrates the original problem. The direct call returns a 404 response without throwing. The function titelLaden() explicitly turns it into an error and cancels the unused body.

Two responses with status 200 fail at different points. At /kaputt the JSON text is incomplete. At /form the JSON is valid, but the number 42 does not fit the text field. Both would pass a status check alone.

Why HTTP 204 also fails this check

HTTP 204 signals success with no body. This status does not indicate a server error. MDN: 204 No Content

Our function expects a JSON object containing a title. An empty response fails at the JSON stage. If an API intentionally permits empty success responses, the caller needs to handle them explicitly. Reading every successful response with json() would be inappropriate for that contract.

The same applies to permitted status codes. ok is a first filter here. An endpoint that must return exactly 200 should specify this in its contract.

Recognise errors and decide how to respond

When designing a screen, first decide which states the user needs to distinguish. “This entry does not exist” and “The service is temporarily unavailable” call for different next steps. Rendering both as an empty list would misrepresent the problem.

The sample messages serve the test. In production, pass structured error categories through the application. Making decisions from message text is fragile. During JSON processing the original cause is retained via cause so other failures may also be reported as unreadable JSON.

Even the final validation has limits. A non-empty title might belong to the wrong record. The application would need to check identifiers or other business rules to detect that case. A correct type alone cannot establish that the content is correct.

The exercise implements no timeout, response-size limit, authentication or retry logic. Running it in Node.js also leaves browser rules such as CORS untested. A production API client needs decisions about these issues for its intended use.

For the transition from prototype to production I would test a successful response alongside an HTTP error, unreadable content and valid JSON with unsuitable data. Each case tests a different assumption in the code.

Sources & further reading

  1. MDN: Window.fetch()
  2. MDN: Response.ok
  3. MDN: Response.json()
  4. MDN: 204 No Content
  5. Node.js HTTP servers and server.close()

Read next

Quick access / The archive

Start here