javascript - 在异步上下文中关闭/卸载时如何处理来自 fetch API 的错误?
问题描述
我将以下代码fetch
写入应用程序中的数据。我想将所有 TypeError: Failed to fetch
抛出的东西包装fetch
到一个专用的应用程序错误对象(FetchError
TypeError
const fetchApi = async (url, init) => {
let response = null;
try {
response = await fetch(url, init);
} catch (e) {
throw new FetchError(`Failed to fetch ${url}`, e);
}
if (response.ok) {
const data = await parse(response);
return { response, data };
} else {
...
}
}
我怀疑浏览器实现(至少 Chrome)在异步上下文中终止,并在关闭或卸载执行我的应用程序的浏览器窗口时fetch
跳过执行以下catch
子句(它实际上是函数的拒绝端)。Promise.then
如何处理这种情况?
解决方案
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
来源:https ://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
你可以尝试这样的事情:
const fetchApi = async (url, init) => {
let response = null;
try {
response = await $.ajax({
url: url
})
return response
} catch (e) {
throw new FetchError(`Failed to fetch ${url}`, e.responseText);
}
}
推荐阅读
- ios - 调整缓冲区大小会导致丢帧
- reactjs - React-Phone-Input-2 自定义焦点输入边框
- c# - 放置清单
在列表视图中 - sql - ORA-00907: 缺少权利专利权
- mysql - 选择带有 2 个表和一个桥表的 COUNT 和 MAX 列
- haskell - 使用 state monad 时的意外行为 - 包含在列表中的状态
- shell - 在makefile中的make命令中传递env变量
- python - 如何从单词列表中不带空格的字符串中获取多个子字符串?
- mysql - MySQL-根据json数组的键值对行进行选择和排序
- c# - 问题从 Blazor 中的数据模型列表生成复选框列表