使用 fetchApi我正在向端点发出 POST 请求并捕获如下错误:
fetch(new Request(url, {
method: 'POST',
headers: { ...defaultHeaders, ...headers } ,
credentials: 'include',
body: JSON.stringify(body)
})).then(
// handle correct reponse
).catch(
if (err.status === 401) {
// handle error nicely
} else if (err.status === 429) {
// handle error differently
} else {
// handle error yet another way
}
);
虽然 401 错误按预期处理,但当端点以 429 代码响应时
else if (err.status === 429) {
// handle error differently
}
永远不会执行。
EDIT1:在 429 的情况下永远不会达到整个捕获量
javascript/浏览器对 401 和 429 状态代码的处理方式是否不同? 如何捕获 429 错误并按我的方式处理?
最佳答案
看起来主要是错误的期望。只有当响应的 type
是 "error"
时,promise 才会被拒绝(因此 catch
被调用),这似乎只是非常具体、有限的案例。
Per MDN, the
fetch()
API only rejects a promise when a “network error is encountered, although this usually means permissions issues or similar.” Basicallyfetch()
will only reject a promise if the user is offline, or some unlikely networking error occurs, such a DNS lookup failure.
换句话说,429响应的请求仍然是成功执行的请求。
The good is news is fetch provides a simple
ok
flag that indicates whether an HTTP response’s status code is in the successful range or not.fetch("http://httpstat.us/500") .then(function(response) { if (!response.ok) { throw Error(response.statusText); } })
关于javascript - HTTP请求错误码429抓不到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240418/