javascript - axios请求: promise error UnhandledPromiseRejectionWarning after catch anyway

标签 javascript node.js error-handling axios es6-promise



我正在尝试正确管理代码中的错误,但收到一条警告,类似于我没有处理被拒绝的 promise ,请参见下文:

UnhandledPromiseRejectionWarning: Error: Request failed with status code 401
at createError (/Users/a/Documents/export/node_modules/axios/lib/core/createError.js:16:15)
at settle (/Users/a/Documents/export/node_modules/axios/lib/core/settle.js:18:12)
at IncomingMessage.handleStreamEnd (/Users/a/Documents/export/node_modules/axios/lib/adapters/http.js:201:11)
at IncomingMessage.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1092:12)
at process._tickCallback (internal/process/next_tick.js:63:19)

这是我的代码:

const axios = require('axios');
axios.get('API_REQUEST', {
    'auth': {
        'bearer': 'NOT_WORKING_TOKEN' // To force the API to return an error ;)
    }
}).catch((error)=>{
    throw error;
})

现在我只想让我的程序在抛出错误时崩溃而不发出警告。

最佳答案

catch block 通常用于从错误中恢复。任何抛出但未在 Promise 链中捕获的错误(在 thencatch 等内部)都将导致 UnhandledPromiseRejection

如果您确定此请求失败不会在您的应用中引入任何未定义的状态,您可以只记录错误而不抛出错误。

.catch(err => logger.error(err)) // or console.error()

如果您坚持要因未处理的拒绝而崩溃,您甚至可以在全局范围内监听该情况,方法是将以下代码放在应用程序入口点周围的某个位置(例如 index.js)

process.on('unhandledRejection', reason => {
    throw reason;
});

另请注意,默认情况下,Node 的 future 版本应该会因未处理的 promise 拒绝而崩溃。

关于javascript - axios请求: promise error UnhandledPromiseRejectionWarning after catch anyway,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52895666/

相关文章:

javascript - 客户端 javascript 找不到我的网址

node.js - 如何在 Facebook Messenger 上使用 MS Bot Framework 创建快速回复?

javascript - 在生产中在 catch block 中放入什么

c# - .net 的错误报告框架

javascript - $ 未定义(SharePoint + JS)

Javascript 与 window.open 链接

php - 字段 'xxx' 没有默认值

javascript - 每个 EmberApp 的单独 index.html 文件

javascript - 如何将json数据转换成BPMN兼容格式?