gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 00:50:17 24 4
gpt4 key购买 nike



我试图在我的代码中正确管理错误,但我收到警告,比如我没有处理被拒绝的 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;
});

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

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

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