首页 文章

如果承诺被拒绝,如何正确抛出错误? (UnhandledPromiseRejectionWarning)

提问于
浏览
2

我有一个承诺,如果承诺被拒绝,我想要抛出异常 . 我试过这个:

var p = new Promise( (resolve, reject) => {
  reject ("Error!");
} );

p.then(value => {console.log(value);});

但是我得到了一个弃用警告:

(node:44056) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error!
(node:44056) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

如果承诺被拒绝,抛出错误的正确方法是什么(以便程序以堆栈跟踪终止)?

我已经尝试在catch子句中插入一个throw语句,但是这会再次产生DeprecationWarning . 实际上(在一些阅读之后),我理解一个catch中的throw会产生对拒绝回调的另一个调用 .

3 回答

  • 1

    您可以捕获unhandledRejection事件以记录堆栈跟踪,前提是您拒绝使用正确的 Error

    var p = new Promise( (resolve, reject) => {
      reject( Error("Error!") );
    } );
    
    p.then(value => {console.log(value);});
    
    process.on('unhandledRejection', e => {
      console.error(e);
    });
    
  • 0

    ...如果承诺被拒绝,程序将以堆栈跟踪终止?

    正是"deprecation"警告告诉你,这正是未来未经处理的承诺拒绝所做的事情 . 请参阅these pull requests了解他们打算做什么,以及the general discussion .

    现在,您可以收听unhandledRejection事件来执行此操作:

    process.on('unhandledRejection', err => {
      console.error(err); // or err.stack and err.message or whatever you want
      process.exit(1);
    });
    
  • 2

    您正在获得DeprecationWarning,因为在解决承诺时添加 catch block 将是强制性的 .

    您可以从catch块内部抛出错误,这样您的程序将以错误的堆栈跟踪终止,如:

    p.then( value => console.log(value) ).catch( e => { throw e });
    

    否则,你可以捕获错误并做一些事情,而不是终止过程,如:

    p.then( value => console.log(value) ).catch( e => { console.log('got an error, but the process is not terminated.') });
    

相关问题