How to handle NetworkError when using Fetch

Nowaday, Fetch API is going to be used widely.

fetch(‘https://awesome.io’)
.then(doSomething)
.catch(error => {})

The most popular polyfill library is isomorphic-fetch which has default behavior is: first, using native fetch, if don’t have, use the polyfill.

Sometimes when you deal with Network problems, you need to know when having a network error.

Luckily, the API has this:

A fetch() promise will reject with a TypeError when a network error is encountered, although this usually means permission issues or similar

(https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)

But it isn’t good enough, because sometimes you have a TypeError inside above `doSomething` function, then this will make your app misunderstand the real problem.

But, we still have another solution:

isNetworkError = hasTypeError(error) && isNetworkErrorMessage(error.message)

With Chrome, the error message will be:

Failed to fetch

With Firefox, it’s:

NetworkError when attempting to fetch resource.

With Safari or other browsers that don’t support fetch, it’s from the polyfill:

Network request failed

(https://github.com/github/fetch/blob/37dcb927ebc2c5282a0840f9ffae9b2fd1b84685/fetch.js#L439)