首页 > 解决方案 > 在异步上下文中关闭/卸载时如何处理来自 fetch API 的错误?

问题描述

我将以下代码fetch写入应用程序中的数据。我想将所有 TypeError: Failed to fetch抛出的东西包装fetch到一个专用的应用程序错误对象(FetchErrorTypeError

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如何处理这种情况?

标签: javascriptasynchronouspromiseasync-awaitfetch

解决方案


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);
    }
}

推荐阅读