gpt4 book ai didi

javascript - 获取 API : how to determine if an error is a network error

转载 作者:行者123 更新时间:2023-12-05 00:27:13 25 4
gpt4 key购买 nike

所以我有一些这样的代码:

async function getData() {
const response = await fetch(/* ... */);
const json = await response.json();
return transform(json);
}

在哪里 transform可以抛出一些自己的错误。

我试图从 fetch 中捕获网络错误API。

try {
const data = await getData();

// ...
return // ...
} catch (e) {
if (isNetworkError(e)) {
return localStorage.getItem('...');
}

throw e;
}

我的问题是如何实现 isNetworkError跨浏览器工作? 注意:这应该只在网络离线时返回 true。

似乎 chrome 和 firefox 都抛出了 TypeError但他们收到的信息各不相同。
  • 火狐:TypeError: "NetworkError when attempting to fetch resource."
  • Chrome :TypeError: Failed to fetch
  • 最佳答案

    如果第一个 Promise 被拒绝,那就是网络错误。那是它唯一的一次。

    The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.



    从 Mozilla 开发者页面:
    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

    关于javascript - 获取 API : how to determine if an error is a network error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61113344/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com