2016-07-07 87 views
4

这是我已经打算:提取:拒绝承诺并在状态不正常时捕获错误?

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

编辑:承诺不被拒绝,这就是我试图找出。

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

+0

你扔在'catch'异常,但不'catch'它。 – zerkms

+0

它*到* catch(捕获所有被拒绝的整个链中的所有拒绝),但catch函数没有处理任何事情 - 它只会重新抛出错误。用'console.error'替换'throw'。 – Bergi

+0

浏览器死机?这绝对不应该发生。 – Bergi

回答

4

感谢大家的帮助,拒绝承诺在.catch()解决我的问题:

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

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

A fetch Response方便地提供了一个ok,告诉你请求是否成功。这样的事情应该做的伎俩:

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) 
}); 
相关问题