Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Fetch Fundamentals

Handling Errors in fetch

Learn why fetch does not reject on 404 or 500, how to check response.ok, tell network failures from HTTP errors, parse error bodies and show friendly messages.

The most surprising thing about fetch() for newcomers is this: a 404 Not Found or 500 Internal Server Error does not make the promise reject. From fetch's point of view, the server answered, and an answer is a success, even when the answer is "no". The promise only rejects when no answer could be obtained at all.

This means there are two completely different kinds of failure to handle: network failures (no response) and HTTP errors (a response with a bad status). On top of that, a third kind hides inside a successful response: a body that is not what you expected. A good request helper treats all three.

We use the small mock server from Your First fetch() Request so every case can be reproduced in the editor, including network failures.

flowchart TD
  A["await fetch(url)"] -->|"rejects"| N["Network failure<br/>TypeError, AbortError"]
  A -->|"resolves"| B{"response.ok?"}
  B -->|"no (4xx, 5xx)"| H["HTTP error<br/>read the error body"]
  B -->|"yes (2xx)"| C["await response.json()"]
  C -->|"throws"| P["Bad body<br/>not valid JSON"]
  C -->|"ok"| S["Success"]

Three places where a request can go wrong, and where each one shows up in your code.

The promise resolves on 404

JS 404 is not a rejection

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The /api/missing case resolves with status 404. Only the offline case rejects. In a real browser the rejection is a TypeError for network failures (DNS error, connection refused, CORS blocked, offline), and a DOMException named AbortError or TimeoutError when you cancel a request (see Cancelling Requests and Timeouts).

Check response.ok

The standard fix is to check response.ok right after the request and throw yourself when it is false. That folds HTTP errors into the same try/catch as network errors.

JS Turning bad statuses into errors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This works, but every failure now looks the same: an Error with a message. Your UI cannot tell "the user does not exist" from "the server is down" without parsing the message string, which is fragile.

A custom error class

A custom error class carries structured information, so the caller can decide what to do with instanceof and properties instead of string matching.

JS HttpError and NetworkError

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at what the code does with the error body: it tries to parse it as JSON and falls back to null. Servers often send a JSON error such as {"error": "..."} or {"errors": {"email": "Taken"}}, but a proxy or crashed server may send HTML or nothing. The error path must never crash because of a surprising error body. The cause property (standard on Error) keeps the original error for debugging.

Turning errors into friendly messages

Users should not see TypeError: Failed to fetch. Map each kind of failure to a message that says what they can do.

JS Friendly messages by status

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two details matter. First, a cancelled request (AbortError) is not an error the user needs to hear about. Second, the technical details still belong in your logs: show friendly text, log the original error.

Only show server-provided error text if your server is designed to send messages for users. Never insert raw error bodies into the page with innerHTML; use textContent (see Rendering API Data in the DOM).

Bad bodies on good responses

Even a 200 OK can contain a body that json() rejects, for example when a proxy or captive portal returns an HTML page with status 200. response.json() then rejects with a SyntaxError. Treat that as a failure too, and consider validating the data after parsing.

JS A 200 that is not JSON

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Checking the Content-Type before calling json() gives a far clearer message than the generic Unexpected token '<' syntax error.

try/catch and the finally block

Use finally for work that must happen on both success and failure, such as hiding a loading spinner. Without it, an error can leave the spinner running forever.

JavaScript
async function loadUser(id) {
  showSpinner();
  try {
    return await request(fetch, '/api/users/' + id);
  } catch (error) {
    showError(friendlyMessage(error));
    return null;
  } finally {
    hideSpinner();
  }
}

Be careful with a very common mistake: forgetting await before the call inside try. return request(...) without await returns the promise before it settles, so a rejection escapes your catch. Writing return await inside try keeps the error inside the block.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A server replies with status 404. What happens to the fetch promise?

    fetch only rejects when no response could be obtained. Any HTTP status, including 404 and 500, resolves normally.
  2. 2. Which situations make a fetch promise reject?

    Rejections represent failure to get a response at all (TypeError) or a cancellation (AbortError, TimeoutError).
  3. 3. Why throw a custom error class like HttpError instead of a plain Error?

    Structured errors let your UI branch reliably on status and body, instead of matching message strings.
  4. 4. What should the error path do when the error body might not be JSON?

    Proxies and crashed servers often return HTML or nothing. The error handler must not crash while handling an error.
  5. 5. Why use a finally block around a request that shows a spinner?

    finally runs whether the try block returned or threw, which is exactly what cleanup code needs.

Summary

  • fetch rejects only when there is no response (network failure) or the request was aborted.
  • HTTP errors resolve normally: check response.ok (or status) and throw yourself.
  • Use custom error classes such as HttpError and NetworkError so callers can branch with instanceof.
  • Parse error bodies defensively and check Content-Type before calling json().
  • Show friendly messages to users, log technical detail, and stay quiet about deliberate cancellations.
  • Use finally for cleanup, and return await inside try so errors are caught.

Next: Sending Data: POST, PUT, PATCH, DELETE.