a paid nerd
a paid nerd

Reputation: 31522

Errors in a promise's error handler go missing

If I throw an error in a promise's catch handler, the error is never bubbled up!

Promise.resolve()
  .then(function() { return foo.bar(); })
  .then(function() { return console.log('ok!'); })
  .catch(function(err) { return baz.quux(); });

In both Node v0.8 with the promise module and Chrome 36's JavaScript console, this prints nothing. I'm expecting to see ReferenceError: baz is not defined appear somewhere.

Shouldn't we see something? Is this a part of the promises spec that I missed?

UPDATE: Clarification: this happens in Chrome 36's V8 without any third-party module.

Upvotes: 2

Views: 480

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276386

Yes, this is a problem promise implementations face. However the two you've chosen fail at it pretty bad. Indeed - the error is swallowed in your case and indeed you will not get any indication of this silent failure unless you attach a error handler yourself.

Your options are:

  • Use a library that offers .done like Q and manually append .done to every single promise in your code to indicate you will not attach handlers to it.
  • Use a library like Bluebird or When that does unhandled rejection detection.

In particular, Bluebird is faster than native promises and does this properly. It is also a superset of native promises so you can write code that uses that subset if you'd like (although it has a much richer API). The code you have above logs an unhandled rejection with Bluebird.

By the way, Firefox handles this much better and Firefox native promises detect unhandled rejections.

Upvotes: 2

Related Questions