gistmax. Back to DiscoverStudio
Technology

Fix fetch code that treats HTTP 404 and 500 as success

By Gistmax Tutorials · 2026-11-04

Web development: Fix fetch code that treats HTTP 404 and 500 as success. Workflow: identify, diagnose, fix, verify.
Web development: Fix fetch code that treats HTTP 404 and 500 as success. Workflow: identify, diagnose, fix, verify.

The page shows a success message even though the API returned an error status. A catch block never runs because the request itself completed over the network.

Why this happens

fetch resolves with a Response for ordinary HTTP error statuses. Network failures and HTTP failures must be handled as distinct outcomes.

Step-by-step solution

1. Check response.ok or the expected status before using the body as successful data.

2. Parse the response according to its content type and handle malformed error bodies. Avoid assuming every reverse-proxy error is JSON.

3. Show a useful failure state and preserve user input for retry. Record a safe request identifier rather than exposing raw server traces.

Worked example

async function readJson(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  return response.json();
}

Verify the fix

Test a successful JSON response, a 404 HTML page, a 500 response and a network disconnect. Only the first should enter the successful rendering path.

Prevent a repeat

Centralise the shared API wrapper and document any expected non-200 success statuses. A successful transport does not imply a successful business operation.

Reference

Official documentation or standards guidance

An original Gistmax troubleshooting guide. Scenarios and sample values are illustrative; configuration depends on your software version and environment. Cover diagram: Gistmax Tutorials.

Join the conversation →