Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch API: how to determine if an error is a network error

So I have some code like this:

async function getData() {
  const response = await fetch(/* ... */);
  const json = await response.json();
  return transform(json);
}

Where transform can throw some of its own errors.


I'm try to catch for network errors from the fetch API.

try {
  const data = await getData();

  // ...
  return // ...
} catch (e) {
  if (isNetworkError(e)) {
    return localStorage.getItem('...');
  }

  throw e;
}

My question is how do I implement isNetworkError that works across browsers? Note: that this should only return true if the network is offline.

It seems like both chrome and firefox throws a TypeError but the messages they have are different on each.

  • Firefox: TypeError: "NetworkError when attempting to fetch resource."
  • Chrome: TypeError: Failed to fetch
like image 674
Rico Kahler Avatar asked Sep 14 '25 16:09

Rico Kahler


2 Answers

When using fetch, you can't differentiate network errors from other errors caused by building an incorrect request, as both are thrown as TypeErrors. (See https://developer.mozilla.org/en-US/docs/Web/API/fetch#exceptions).

This is quite a flaw, as application defects that cause an incorrectly built request may go unnoticed, masked as if they were circumstantial network errors.

like image 195
Ernesto Avatar answered Sep 16 '25 05:09

Ernesto


If the first promise rejects, it's a network error. That's the only time it does.

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

From Mozilla developer page: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API


Edit: As pointed out in the comments and other answers, you should also pay attention to the line "or if anything prevented the request from completing". Which means that the initial Promise of fetch will reject on network errors in addition to other problems. Like for example, an invalid URL or a CORS error.

If fetch is able to successfully reach the server with your request, it will resolve the first Promise successfully, otherwise the first promise will reject. In the case of CORS, the error occurs before your request is actually sent out (in the OPTIONS request), which is why the error occurs in the first Promise.

like image 20
Zachary Haber Avatar answered Sep 16 '25 05:09

Zachary Haber