【问题标题】:Axios request : promise error UnhandledPromiseRejectionWarning after catch anywayAxios 请求:无论如何在捕获后承诺错误 UnhandledPromiseRejectionWarning
【发布时间】:2019-03-24 12:58:24
【问题描述】:



我正在尝试在我的代码中正确管理错误,但我收到了一个警告,比如我没有处理被拒绝的承诺,见下文:

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

现在我只想让我的程序在抛出错误时在没有警告的情况下崩溃。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    如果您坚持因未处理的拒绝而崩溃,您甚至可以通过将以下代码放在应用程序入口点周围的某处(例如 index.js

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

    另外请注意,Node 的未来版本默认会在未处理的 Promise 拒绝时崩溃。

    【讨论】:

    • 嘿,谢谢您的回答,遗憾的是我的代码应该在 AWS 的 lambda 函数中运行,因此 process.on('unhandledRejection') 在他们的环境中无法访问(我没有找到等价物)axios.get('api_request', { 'auth': { 'bearer': 'Wrong_token' } }).then((res)=>{ console.log("RES HERE"); }).catch((error)=>{ console.log("ERROR FOUND"); throw error; }) 我仍然得到ERROR FOUND (node:2508) UnhandledPromiseRejectionWarning: Error: Request failed with status code 401 这意味着捕获正在起作用,所以我不明白哈哈
    • @Amo 我的想法是,您可以选择不将错误扔到 catch 处理程序中来记录错误而不会崩溃。有点像“嘿,这失败了,我知道,我会记录下来,但我的应用程序并不关心这个足以崩溃”。如果您选择 throw,则无需额外记录错误。
    • @Amo 同样,process.on('unhandledRejection') 在 aws lambda 中工作。您可以使用处理程序代码在文件中设置侦听器。我相信,将其设置在实际的处理函数之外效果最好,因为我们不想在单个进程中为同一事物设置多个侦听器。所以就在你的处理程序上方的文件顶部的某个地方,在你的导入之后。
    • 好的,重点是我在 AWS 中使用 Lambda 函数从 API 加载大量数据。它需要足够长的超时时间以允许 Lambda 加载所有数据。但是,如果发生错误并且我得到了这个UnhandledPromiseRejection,则 lambda 在停止自身之前等待超时,并且我支付所有无用的执行时间......这就是为什么我希望 lambda 在发生错误时立即崩溃而不是只是一个日志:/.
    • 现在我在处理程序之外尝试了process.on('unhandledRejection'),它成功了(谢谢你;))但是我怎样才能得到正确的错误而不是"errorMessage": "RequestId: 374cb64d-d3d1-11e8-99b9-9ddc5d4dec4e Process exited before completing request"?谢谢你的时间;)!
    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 2020-07-30
    • 2021-07-27
    • 2018-09-25
    • 1970-01-01
    • 2022-08-03
    • 2020-11-27
    • 2020-10-30
    相关资源
    最近更新 更多