Fetch: reject promise and catch the error if statu

2019-03-14 12:23发布

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.

3条回答
趁早两清
2楼-- · 2019-03-14 12:27

Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

export 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 => {
                    return Promise.reject()
                })
            });
    };
}


function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    }
    return res;
}
查看更多
小情绪 Triste *
3楼-- · 2019-03-14 12:36

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();
  } else {
    throw new Error('Something went wrong');
  }
})
.then((responseJson) => {
  // Do something with the response
})
.catch((error) => {
  console.log(error)
});
查看更多
戒情不戒烟
4楼-- · 2019-03-14 12:48

I just checked the status of the response object:

$promise.then( function successCallback(response) {

  console.log(response);

  if( response.status === 200 ) { ... }

});
查看更多
登录 后发表回答