Edit
We've finally fixed this in Node.js 15, it took 5 years but native promise rejections now behave like uncaught exceptions - so it's fine to just add a process.on('uncaughtException'
handler.
In Modern Node.js
Starting with io.js 1.4 and Node 4.0.0 you can use the process
"unhandledRejection"
event:
process.on("unhandledRejection", function(reason, p){
console.log("Unhandled", reason, p); // log all your errors, "unsuppressing" them.
throw reason; // optional, in case you want to treat these as errors
});
This puts an end to unhandled rejections problems and the difficulty of tracking them down in your code.
In Older NodeJS
These events were not yet back-ported to older versions of NodeJS and are unlikely to be. You can use a promise library that extends the native promise API such as bluebird which will fire the same events as there are in modern versions.
It's also worth mentioning that there are several userland promise libraries that offer the unhandled rejection detection facilities and much more such as bluebird (which also has warnings) and when.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…