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

时间:2017-08-19 11:31:40

标签: javascript es6-promise

我有一个承诺,如果承诺被拒绝,我希望抛出异常。我试过这个:

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 个答案:

答案 0 :(得分:2)

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

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

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

process.on('unhandledRejection', e => {
  console.error(e);
});

答案 1 :(得分:1)

  

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

正如“弃用”警告告诉你的那样,这正是未来未经处理的承诺拒绝所做的事情。见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 :(得分:0)

您正在获得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.') });