Search code examples
node.jsexceptionpromiseunhandled-promise-rejection

Why is make-promises-safe only for use in "in top-level program code"


The make-promises-safe package changes Node.js's default behavior with regards to errors thrown in promises. Normally, in Node, these unhandled promise rejections will be logged, but a program keeps on running. With make-promises-safe installed, Node.js will exit when it encounters an unhandled promise rejection. The "safe" here means that your program won't have secret unhandled rejections, since unhandled rejections often line up with resources that have not been properly cleaned up, and these non-cleaned up resources can cause problems in a long running program.

All that I understand. However, this module comes with a warning

It is important that this module is only used in top-level program code, not in reusable modules!

The purpose of this warning is unclear. Why is it that the module authors advise folks against using this module in their own reusable modules?


Solution

  • I think the warning could indeed use some additional clarification if only to clarify the use of the slightly confusing terms of reusable modules and top-level program code here.

    When I read the warning I felt like it was warning against using it in packages/modules you publish to npm. When a user imports your npm package (which might be totally unrelated to error-handling) in which you required the make-promises-safe package, this would implicitly impose an error-handling mechanism the user might not be aware of. You could add this to your README file of course but not everybody reads those thoroughly.

    As you discussed in the comment section of your question already, the source code shows that it subscribes to the unhandledRejection event but even though it might not be as clean to require the make-promises-safe multiple times, the way it is declared, the module caching should indeed prevent the binding from happening more than once. So I would not count that as an issue. On the other hand, if every module started requiring make-promises-safe of course, there would be multiple subscriptions to the event.

    So, conclusion. I would only require make-promises-safe in the entry file of your node application (fe. app.js/server.js where your register create/configure your http server for a node web application), so, code you have control over yourself as the developer. I would not require it in any node module (be it locally or publicly on npm) and leave it to the user that implements your package how to handle errors in HIS application.