JavaScript Fetching External Data

Fetch error handling

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.

MDN (Fetch API)

Which means that we cannot rely on the fetch Promise to be rejected when the response from the server indicates that an error happened. We instead have to use the ok property to correctly check for errors before we continue our chain of promises.

Generic error handler

It is usually a good idea to write a generic error handler for fetch that promotes all non-ok responses to failures.

const handleErrors = response => {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}

We can then use this function as the first handler in the Promise chain after the fetch call as shown below.

fetch("/cars/23")
.then(handleErrors)
.then(response => response.json())
.then(console.log)