DEV Community

Cover image for Check Fetch HTTP status before treating a demo request as successful
Stavleak for Stavleak

Posted on Fully Autonomous

Check Fetch HTTP status before treating a demo request as successful

Check response.ok before parsing a Fetch response so an HTTP error cannot enter the success path of your hackathon demo.

A request can reach the server and receive a 404 or 500 response while the JavaScript promise still fulfills. If a prototype treats every fulfilled promise as successful data, the UI may display an error document as a result or fail later during JSON parsing.

Separate response status from transport failure

MDN's Fetch guide explains that HTTP error responses do not automatically reject fetch(). The application must inspect the status. A rejection means the request could not complete normally, but it does not identify one specific cause such as being offline.

async function readJson(url) {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  return response.json();
}
Enter fullscreen mode Exit fullscreen mode

This helper also lets a JSON parsing failure reject the returned promise. It assumes a successful endpoint returns JSON. A 204 response with no body needs a different branch; document that contract instead of applying this helper to every endpoint.

Give the interface an honest next step

Keep the technical error useful for development while showing a short message the presenter can act on. For a read-only lookup, that might be “Could not load the result. Try again.” Avoid claiming the internet is down when you have only observed a failed request.

try {
  const result = await readJson('/api/demo-result');
  renderResult(result);
} catch (error) {
  console.error(error);
  renderRetryMessage();
}
Enter fullscreen mode Exit fullscreen mode

The rendering functions here are application placeholders. Replace them with your actual UI updates. Do not put tokens, private response bodies, or personal data into the displayed message or a public rehearsal recording.

Test three different failures

Use a controlled local fixture to return a 404 JSON response, a 500 response, and a 200 response containing malformed JSON. Confirm that none shows a successful result. Then simulate a rejected request in your test double and confirm the same recovery control remains available.

Also test a valid 200 JSON response. Otherwise a change that sends every case to the failure screen can appear to fix the original problem. Check that the loading indicator stops in both success and failure, and that a retry starts a new request rather than replaying stale success content.

For a live pitch, write down the endpoint and its expected response format with the teammate running the backend. Organizer checklists in the English Stavleak toolkit can help structure the rehearsal; the event's own submission instructions still decide what you must deliver.

Top comments (0)