【问题标题】:How to wrap JavaScript fetch in a function - unhandled promise rejection如何将 JavaScript fetch 包装在函数中 - 未处理的承诺拒绝
【发布时间】:2019-06-02 02:49:06
【问题描述】:

我正在尝试为 JavaScript fetch 命令编写一个包装函数。

我从this post获取示例代码:

function fetchAPI(url, data, method = 'POST') {
const headers = {
    'Authorization': `Token ${getAuthToken()}`,
};

return fetch(url, { headers, 'method': method, 'body': data })
    .then(response => {
        if (response.ok) {
            const contentType = response.headers.get('Content-Type') || '';

            if (contentType.includes('application/json')) {
                return response.json().catch(error => {
                    return Promise.reject(new Error('Invalid JSON: ' + error.message));
                });
            }

            if (contentType.includes('text/html')) {
                return response.text().then(html => {
                    return {
                        'page_type': 'generic',
                        'html': html
                    };
                }).catch(error => {
                    return Promise.reject(new Error('HTML error: ' + error.message));
                });
            }

            return Promise.reject(new Error('Invalid content type: ' + contentType));
        }

        if (response.status === 404) {
            return Promise.reject(new Error('Page not found: ' + url));
        }

        return response.json().then(res => {
            // if the response is ok but the server rejected the request, e.g. because of a wrong password, we want to display the reason
            // the information is contained in the json()
            // there may be more than one error
            let errors = [];
            Object.keys(res).forEach((key) => {
                errors.push(`${key}: ${res[key]}`);
            });
            return Promise.reject(new Error(errors)
            );
        });
    }).catch(error => {
        return Promise.reject(new Error(error.message));
    });

};

我这样称呼它:

fetchAPI('/api/v1/rest-auth/password/change/', formData).then(response => {
        console.log('response ', response);
    });

编辑:如果请求正常但被拒绝(例如由于密码无效),我已修改代码以显示服务器返回的信息。如果 ok == false,您必须询问响应 json。

有效的 URL 获取是可以的。但如果出现错误,我会看到 Unhandled Rejection (Error): 错误消息。

为什么即使它们在 catch 块中,也没有处理拒绝?这里的秘诀是什么?

【问题讨论】:

  • 你处理错误,然后重新抛出错误,然后没有得到处理。又名。 Unhandled Rejection (Error)ps。 .catch(error => { return Promise.reject(new Error(error.message)); }); 并没有真正有用。
  • 您是否尝试在调用代码fetchAPI(...).then(...).catch(...) 上添加.catch(...)
  • @Keith,我在很多例子中都看到过这种格式,它是否从根本上是错误的,如果是这样,为什么它如此普遍?您建议如何在 fetchAPI 函数中处理错误情况?通知调用函数错误并将错误消息传递给它的正确方法是什么?
  • @LittleBrain 我认为您的操作方式本身没有任何问题,您只需要记住处理来自调用者的可能异常(或者,接受未处理的拒绝消息)跨度>
  • @Jamiec,谢谢!这是令人困惑的,因为错误似乎在 fetchAPI 函数中......嗯,它是,但它是没有处理它的调用函数。这对我来说更清楚了。

标签: javascript promise fetch


【解决方案1】:

避免未处理的承诺拒绝的方法是处理它:

fetchAPI('/api/v1/rest-auth/password/change/', formData).then(response => {
    console.log('response ', response);
}).catch(error => {
   // do something meaningful here.
});;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2023-03-17
    • 2018-04-01
    • 2021-09-19
    相关资源
    最近更新 更多