javascript - HTTP请求错误码429抓不到

标签 javascript http fetch-api

使用 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.” Basically fetch() 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);
        }
    })

https://www.tjvantoll.com/2015/09/13/fetch-and-errors/

关于javascript - HTTP请求错误码429抓不到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240418/

相关文章:

javascript - 通过java脚本点击电子邮件地址时如何重定向到电子邮件地址?

javascript - Google Geochart - 来自 JSON 数据的相同国家/地区多个值

javascript - 如何检测浏览器中 AJAX (XmlHttpRequest) 调用的超时?

javascript - 从 php 中的循环填充的表格中的模态表单触发按钮

jquery - ajax请求失败条件

linux - cookie 是如何工作的

html - 支持多种设备的 HTTP 实时流式传输

javascript - React-native 上传图片到 amazon s3

javascript - Axios 与 Fetch 中如何处理网络错误?

javascript - 如何跨多个页面获取数据?