【问题标题】:UnhandledPromiseRejection despite catching expection尽管捕获异常,但未处理的 Promise Rejection
【发布时间】:2021-05-18 09:40:28
【问题描述】:

在下面的代码中

// file: main.js
    class A {
    
        async start() {
            
            throw 'error';
        }
    }
    
    module.exports = A;



// file index.js

    var r = require('./main.js'); 
    
    let v = new r();
    
    try {
        v.start(); // error is caught when I use r.start() though
    } catch (e) {
        console.error(e);
    }

我是 Javascript 和 Node.js 的新手,当我清楚地捕捉到异常时,Node.js 会抛出 UnhandledPromiseRejection,为什么会发生?

【问题讨论】:

  • 一个async 函数总是返回一个异步的promise。建议你研究一下如何捕获 promise 错误
  • @charlietfl 感谢您的指出,我添加了 await 并且它起作用了,但是只是好奇它在我直接调用它而不创建实例的情况下在没有 await 的情况下起作用,为什么?对于参考,请参阅编辑的代码

标签: javascript node.js exception es6-promise unhandled-promise-rejection


【解决方案1】:

此错误源于在没有 catch 块的情况下抛出异步函数

查看原因:

node --trace-warnings index.js

【讨论】:

    猜你喜欢
    • 2020-06-21
    • 1970-01-01
    • 2013-12-13
    • 2018-01-11
    • 2012-02-01
    • 1970-01-01
    • 2017-11-25
    • 2017-11-17
    • 2020-08-30
    相关资源
    最近更新 更多