← All posts

JavaScript fetch doesn’t throw on 404 or 500: handling errors properly

Why the try/catch around your fetch() call never sees a 404 or a 500, and how to write complete error handling: HTTP status, error bodies, network failures, timeouts, retries and a message the user can actually act on.

JavaScript fetch doesn't throw on 404 or 500: handling errors properly

Key points

  • fetch() only rejects when the network request itself fails. As far as it’s concerned, a 404 or a 500 is a success, so you have to check response.ok.
  • A small helper that tells network errors, timeouts and HTTP errors apart saves you repeating the same logic on every call.
  • Only retry transient errors, and never retry a request that creates or charges something unless the server guarantees idempotency.

It’s one of the most common JavaScript traps, and it catches experienced developers too, especially those coming from axios or jQuery: a fetch() call wrapped in try/catch, an API that returns a 500, and no error caught. The code carries on, tries to parse JSON that isn’t JSON, and the error that eventually shows up in the console (“Unexpected token ‘<‘”) points nowhere near the real cause. In the code audits we run, it turns up in almost every project that calls fetch directly. Here’s why it happens, and how to put proper error handling in place once and for all.

Why fetch doesn’t reject on a 404 or 500

The promise returned by fetch() answers a single question: did we get an HTTP response? If the server answers at all, even with a 404, 403 or 500, the promise resolves with a Response object. It only rejects when no response could be obtained: the network is down, the domain can’t be resolved, CORS blocks the request, or the request was aborted.

// Looks fine… and never catches a 404 or a 500
try {
  const res = await fetch('/api/products/42');
  const product = await res.json();
  render(product);
} catch (e) {
  showError('Could not load the product');
}

With this code, a 500 doesn’t reach the catch when the call is made. It gets there later, for the wrong reason: the server’s error page is often HTML, and res.json() fails trying to parse it. If the server sends a JSON error instead, say {"message": "Product not found"}, there’s no error at all: the code renders an empty product and nobody notices.

This is by design. A 404 is a perfectly valid response at the protocol level, and it’s up to your code to decide what it means. Axios made the opposite choice, hence the confusion when switching between them.

Check response.ok, and read the error body

res.ok is true for statuses 200 to 299 and false for everything else. Check it every time, before reading the body:

const res = await fetch('/api/products/42');

if (!res.ok) {
  // res.status: 404, 422, 500…; the body often holds the details
  const detail = await res.text();
  throw new Error(`HTTP ${res.status} on ${res.url}: ${detail.slice(0, 200)}`);
}

const product = await res.json();

Two details matter in practice. First, the error body is valuable: most APIs explain the refusal there (missing field, expired token, quota reached). Throwing it away means throwing away what you need to debug. Second, a response body can only be read once. Call res.text() and then res.json() on the same response and the second call fails. Pick the method based on the Content-Type header, or use res.clone() if you really need both.

Watch out for 204 (No Content) as well: it’s a success, but there’s no body, so res.json() throws. You’ll see it a lot on DELETE requests.

One helper for every call

Repeating those checks on every call is tedious, and sooner or later one gets missed. On our projects we put the logic in one small function that returns the data on success and throws a typed error otherwise:

export class HttpError extends Error {
  constructor(response, body) {
    super(`HTTP ${response.status} ${response.statusText}`);
    this.name = 'HttpError';
    this.status = response.status;
    this.body = body; // JSON object if the API sends one, text otherwise
  }
}

export async function request(url, { timeout = 10000, ...options } = {}) {
  let res;
  try {
    res = await fetch(url, {
      ...options,
      headers: { Accept: 'application/json', ...options.headers },
      signal: options.signal ?? AbortSignal.timeout(timeout),
    });
  } catch (e) {
    // Network down, DNS, CORS refused, timeout: no response at all
    if (e.name === 'TimeoutError') throw new Error('The server is taking too long to respond', { cause: e });
    throw new Error('Could not reach the server', { cause: e });
  }

  const type = res.headers.get('Content-Type') ?? '';
  const body = res.status === 204 ? null
    : type.includes('application/json') ? await res.json().catch(() => null)
    : await res.text();

  if (!res.ok) throw new HttpError(res, body);
  return body;
}

It separates three kinds of failure, each calling for a different response:

  • No response at all (network, DNS, CORS): the user may be offline or the API unreachable. Trying again later makes sense.
  • Timeout: AbortSignal.timeout(), available in every current browser, aborts the request after the given delay. Without it, fetch can wait a very long time for an answer that never comes, leaving your UI stuck on a spinner.
  • HTTP error: the server answered but said no. HttpError carries the status and the body, so calling code can respond precisely.

The cause option keeps the original error for your logs, while the user sees a readable message.

Respond according to the kind of error

With a typed error, calling code becomes easy to read: each status that means something to the user gets its own handling, and everything else falls through to a generic message.

import { request, HttpError } from './request.js';

try {
  const cart = await request('/api/cart', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ product: 42, quantity: 1 }),
  });
  updateCart(cart);
} catch (e) {
  if (e instanceof HttpError && e.status === 422) {
    showFieldErrors(e.body?.errors);         // validation error: explain it
  } else if (e instanceof HttpError && e.status === 401) {
    location.assign('/login?return=' + encodeURIComponent(location.pathname));
  } else {
    showMessage('Your cart could not be updated. Please try again in a moment.');
    console.error(e);                              // details for you, not for the customer
  }
}

The mappings we use most often:

  • 400 and 422: validation errors. Show the API’s messages next to the relevant fields; it’s the only kind of error users can fix themselves.
  • 401: the session expired. Redirect to the login page and remember where they were, instead of showing “unknown error”.
  • 403: logged in, but not allowed. Say so plainly; it’s not a glitch worth retrying.
  • 404: the resource doesn’t exist, or no longer does (deleted product, old link). Offer an alternative.
  • 429, 502, 503, 504: overload or temporary unavailability. This is the family that justifies an automatic retry.
  • 500: a server-side bug. A generic message for the user, full details in your logs.

Never show users the raw body of a server error. It can contain file paths, SQL queries or stack traces: useless to them, and an information leak.

For 429, 502, 503 and 504, an automatic retry with a growing delay (one second, then two, then four) often sorts things out, with one condition: only retry reads, or operations the server can replay without creating a duplicate. A timeout on a payment POST doesn’t mean the payment failed; the response may simply have got lost, and a blind retry risks charging the customer twice. If the server sends a Retry-After header, honour it.

FAQ

Why do I get “Unexpected token ‘<‘”?

Because res.json() is trying to parse HTML as JSON. It’s almost always an error page (404, 500) or a login page sent back in place of your data. Check res.ok and the Content-Type header before reading the body, and look at the actual response in the Network tab of your dev tools.

Can I catch and inspect a CORS error?

You can catch it, but not inspect it. For security reasons the browser only hands your script a generic TypeError, with no status and no details. The Console and Network tabs are the only way to diagnose it, and the fix belongs on the server, in its CORS headers.

Is your app showing blank screens or baffling errors whenever an API misbehaves? We audit and harden the JavaScript behind websites and web applications. Tell us about your project.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →