获取:拒绝承诺并在状态不正常时捕获错误? [英] Fetch: reject promise and catch the error if status is not OK?

查看:19
本文介绍了获取:拒绝承诺并在状态不正常时捕获错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要做的:

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;
}

承诺不会被拒绝,这就是我想要弄清楚的.

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

我在 Redux 中使用这个 fetch polyfillredux-promise-middleware.

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

推荐答案

Fetch 承诺仅在发生网络错误时使用 TypeError 拒绝.由于 4xx 和 5xx 响应不是网络错误,因此没有什么可捕获的.您需要自己抛出错误才能使用 Promise#catch.

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.

fetch Response 方便地提供了一个 ok ,它告诉你请求是否成功了.这样的事情应该可以解决问题:

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)
});

这篇关于获取:拒绝承诺并在状态不正常时捕获错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆