Kuba Orlik
Kuba Orlik

Reputation: 3500

Exceptions not shown when raised inside a promise

I'm developing a node module that heavily relies on Promises. For some reason, when an exception should be raised within a Promise code (e.g. "undefined is not a function"), the exception message is not displayed in the console - the promise chain just seems to stop without any feedback and all I can do is guess what's causing that. How can I force Node to show all exceptions?

Upvotes: 2

Views: 221

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276536

Promises are throw safe - that is they convert throws to rejections. If an exception is thrown inside a then you get a rejected promise and you can recover rather than crash your entire server.

Older promise libraries as well as native promises don't feature "unhandled rejection tracking" and will basically suppress your errors. Newer libraries feature "unhandled rejection tracking" which does not exhibit the behavior you describe.

Your options are:

  • Use a new library like Bluebird promises which will log unhandled rejections to your console. That is - the library practically solves the issue for you.
  • In some libraries, you can use .done at the end of the promise chain to convert unhandled rejections to thrown exceptions.
  • With native promises this is a real, painful and open issue. You have to add .catch(function(e){ setTimeout(function(){ throw e; }); }) that is - explicitly unsafely throw and cause the error to show. You have to do this for every promise chain end. I find this very irritating personally.

Note that it is expected that v8 will eventually solve this and behave similarly to bluebird promises, we however don't have a deadline yet. Generally it is my opinion that native promises are not ready for prime time in node yet and it is preferable to use a strong library.

Upvotes: 2

Related Questions