Search code examples
javascriptreduxfetch-api

Fetch: reject promise and catch the error if status is not OK?


Here's what I have going:

import 'whatwg-fetch';

function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())            
                .catch(error => {
                    throw(error);
                })
            });
    };
}

function status(res) {
    if (!res.ok) {
        return Promise.reject()
    }
    return res;
}

EDIT: The promise doesn't get rejected, that's what I'm trying to figure out.

I'm using this fetch polyfill in Redux with redux-promise-middleware.


Solution

  • Fetch promises only reject with a TypeError when a network error occurs. Since 4xx and 5xx responses aren't network errors, there's nothing to catch. You'll need to throw an error yourself to use Promise#catch.

    A fetch Response conveniently supplies an ok , which tells you whether the request succeeded. Something like this should do the trick:

    fetch(url).then((response) => {
      if (response.ok) {
        return response.json();
      }
      throw new Error('Something went wrong');
    })
    .then((responseJson) => {
      // Do something with the response
    })
    .catch((error) => {
      console.log(error)
    });