how to properly throw an error if promise is rejected? (UnhandledPromiseRejectionWarning)

别等时光非礼了梦想. 提交于 2019-11-29 15:46:17

You can catch unhandledRejection events to log an stack trace, provided that you reject using a proper Error:

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

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

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

…so that the program is terminated with a stack trace if the promise is rejected?

That's exactly what unhandled promise rejections will do in the future, as the "deprecation" warning is telling you. See these pull requests for what they plan to do, as well as the general discussion.

For now, you can listen to unhandledRejection events to do this:

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

You are getting DeprecationWarning because adding catch block while resolving promise is going to be mandatory.

You can throw the error from inside catch block, this way your program will be terminated with the error's stack trace, like:

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

Else you can catch the error and do some stuff while not terminating the process, like:

p.then( value => console.log(value) ).catch( e => { console.log('got an error, but the process is not terminated.') });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!