【发布时间】:2016-09-29 06:17:48
【问题描述】:
我正在尝试找到一种处理我认为错误的 http 响应的好方法。我在 React Native 中使用 fetch。这是我的代码。
loginRequest(url) {
return fetch(url, {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;'
},
....
})
.then(response => {
return this.processResponse(response);
});
}
那么……
processResponse(response) {
if (response.status === 200) {
return response.json();
} else {
let error = new Error(response.status);
error.response = response.json(); // This is the problem
error.status = response.status;
throw error;
}
},
上面是这样调用的:
return ApiRequests.loginRequest(username, password)
.then(json => {
dispatch(Actions.loginSuccess(json, username, password));
})
.catch(error => {
dispatch(Actions.loginFailure(error));
});
};
我的想法是我可以在 catch 中轻松地分别处理所有错误(我们假设除了 200 错误之外的任何错误)。问题是 response.json() 返回一个承诺,因此将其分配给 error.response 不起作用。我需要跟踪 http 状态代码和响应正文。
【问题讨论】:
-
尝试拒绝 Promise 而不是抛出错误,可能是:
Promise.reject(new Error(response.statusText)),developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… -
会检查一下谢谢
标签: javascript react-native fetch es6-promise