throw-rejects1.0.0 • Public • Published
Throw unhandled Promise rejections
Fixes error handling for Promises, including the swallowed error problem, by converting unhandled rejections into normal thrown exceptions. Ensures that the process crashes correctly, just like throwing non-Promise errors does.
Tip: Be a good citizen and only use this in top level packages like apps and CLIs, as opposed to libraries, to avoid surprising any dependents.
- Promises do not distinguish between operational and programmer errors.
- Unhandled rejections are usually accidental programmer errors.
- By default, Node doesn't even tell you about these errors.
.catch() handlers asynchronously is almost always a bad idea and programs can be designed to avoid doing so. Crashing with a stack trace, as this module does, is a much more safe and helpful default behavior, as opposed to doing nothing and hoping that maybe someone will handle the error in the future.
You can still use
.catch() to avoid crashing, see usage for details.
npm install throw-rejects --save
Get it into your program.
const throwRejects = ;
Activate the listener, which will convert unhandled Promise rejections into thrown exceptions. We recommend doing this as early as possible, in case your other dependencies use Promises.
Or, you can shorten this by calling the function immediately.
Alternatively, use the register script, which self-activates as a side effect.
register script is especially useful for modules using
import, because that syntax does not allow immediate function calls. Thus, importing
register is the shortest syntax in that environment.
After the listener is activated, you can still handle errors yourself to avoid crashing, as long as you don't do something weird like reject a Promise and then start a timeout which adds the
.catch() 5 seconds later, for example.
// Will crash with throw-rejects.// Will NOT crash without throw-rejects.const prom = Promise;
const prom = Promise;// Prevents throw-rejects from crashing the process.// Will NOT crash, with or without throw-rejects.prom;
const prom = Promise;;
Specifically, rejections will be considered handled and the process will not crash as long as you add
.catch() anytime within the same event loop as the Promise is rejected, That is basically anywhere you would normally do so. It doesn't have to be chained directly, it can be later in a function, etc.
Activates a listener for
unhandledRejection events that throws the associated error as an exception. This will, in turn, bubble up to
uncaughtException and, by default, crash the process and print a stack trace.
See our contributing guidelines for more details.
- Fork it.
- Make a feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request.
Go make something, dang it.