Javascript 如何处理ES6承诺中的错误状态?
我正在使用ES6并尝试处理Javascript 如何处理ES6承诺中的错误状态?,javascript,es6-promise,fetch-api,Javascript,Es6 Promise,Fetch Api,我正在使用ES6并尝试处理fetch()结果的错误状态 我知道我可以捕捉到这样的错误: fetch(`http://${this.serverAddress}/reset`) .then((resp) => { Logger.debug(JSON.stringify(resp)); }) .catch((err) => { Logger.debug(JSON.stringify(err))
fetch()
结果的错误状态
我知道我可以捕捉到这样的错误:
fetch(`http://${this.serverAddress}/reset`)
.then((resp) => {
Logger.debug(JSON.stringify(resp));
})
.catch((err) => {
Logger.debug(JSON.stringify(err));
});
在catch
块中,我接收到一个错误
,消息为“无法获取”。没有状态信息
我发现以下建议:
fetch('/some/url/')
.then(processResponse)
.then(response => {
// do something
})
.catch(response => {
// repsonses with status >= 400 get rejected. you can access response.status and response.data here too
if (response.status === 400) {
// handle form validation errors, response.data.errors...
} else if (response.status === 403) {
// handle permission errors
} // etc
});
但是response.status
在catch
块中未定义
如何获取错误的状态代码来处理它
更新:
谢谢你的回复。请查看我的更新:
我的实际令牌看起来是http://api.service/v2/prices/latest?token=err
。如果我写我的令牌而不是err
,那么它就工作了。当我尝试此URL时,我的代码会转到catch
块,而不是then
我在浏览器控制台中注意到以下错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
如果我添加{mode:“no cors”}
,则代码转到,然后
,但状态始终为0。这不是我想要的
我试图补充
mode: "cors",
headers: {
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
}
这没有帮助,我仍然有
No'Access Control Allow Origin'标题
错误。如文档中所示,只有在请求未完成时才会到达catch
块。当有可用的状态代码时(同时也收到所有其他数据)fetch
将被解析,因此将到达块
从fetch()返回的承诺不会在HTTP错误状态下拒绝,即使响应是HTTP 404或500。相反,它将正常解析(ok status设置为false),并且它只会在网络故障或任何阻止请求完成的情况下拒绝。-
因此,您所要做的就是记录resp.status
,而不是resp
fetch(`http://${this.serverAddress}/reset`)
.then((resp) => {
Logger.debug(JSON.stringify(resp.status));
})
.catch((err) => {
Logger.debug(JSON.stringify(err));
});
在catch块中,我接收到一个错误消息“未能获取”。没有状态信息
因此,如果调用catch
块,请求甚至没有完成。这可能是因为您没有使用诸如方法
,标题
,。。。如果需要,哪一个和什么值取决于您使用的后端。您不能在代码中检查状态
从fetch()返回的承诺不会在HTTP错误状态下拒绝
即使响应是HTTP 404或500。相反,它会解决问题
正常情况下(ok状态设置为false),它只会在
网络故障或任何阻止请求完成的情况
基本上,fetch()只会在出现网络错误时拒绝承诺
fetch API提供了一个简单的ok标志,指示HTTP响应的状态代码是否在成功范围内。请参见下面的示例
fetch("http://httpstat.us/500")
.then(function(res) {
if (!res.ok) {
throw Error(res.statusText);
}
return res;
}).then(function(res) {
console.log("ok");
}).catch(function(error) {
console.log(error);
});
您可以在使用完成提取后立即在响应处理过程中抛出错误,从而尝试处理错误状态!好的
:
fetch('/some/url/')
.then(response => {
if (!response.ok) {
throw Error({ status: response.status });
}
response.json();
})
.then(response => {
// do something
})
.catch(error => {
switch(error.status) {
// ...
}
});
获取请求后,检查响应是否符合预期。如果不是,则抛出带有自定义消息的新错误。在catch中,检查抛出的错误是否存在此自定义消息。相应地处理。
您还可以创建自定义错误并进行检查。您应该在processResponse
中进行检查,它可以访问response
对象(并且您可以返回Promise.reject(…)
,随您所需),可以检查状态代码。虽然不在catch
块内,但在then
块内。