Emanuele Paolini
Emanuele Paolini

Reputation: 10172

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

I have a promise and I would like an exception to be thrown if the promise is rejected. I tried this:

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

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

but I get a DeprecationWarning:

(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.

What is the correct way to throw an error (so that the program is terminated with a stack trace) if the promise is rejected?

I already tried to insert a throw statement in a catch clause, but this again produces a DeprecationWarning as before. In fact (after some reading) I understand that a throw in a catch produce another call to the reject callback.

Upvotes: 4

Views: 5057

Answers (3)

Bergi
Bergi

Reputation: 665276

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

Upvotes: 2

robertklep
robertklep

Reputation: 203514

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

Upvotes: 2

Raghav Garg
Raghav Garg

Reputation: 3707

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

Upvotes: 0

Related Questions