如何使用node.js中的本机承诺全局处理异常? [英] How do I handle exceptions globally with native promises in node.js?
问题描述
我知道如何处理承诺中的特定错误,但是我有时有些代码看起来像这样:
I know how to handle specific errors in promises but I sometimes have pieces of code that looks like this:
somePromise.then(function(response){
otherAPI(JSON.parse(response));
});
有时,我得到无效的JSON,这会在JSON.parse
throw
s时在此处导致无提示失败.通常,我必须记住在代码中的每个诺言中都添加一个.catch
处理程序,否则,我将无法找出忘记了诺言的地方.
Sometimes, I get invalid JSON which causes a silent failure here when JSON.parse
throw
s. In general I have to remember to add a .catch
handler to every single promise in my code and when I don't I have no way to find out where I forgot one.
如何在代码中找到这些被抑制的错误?
How do I find these suppressed errors in my code?
推荐答案
在现代NodeJS中
从io.js 1.4和Node 4.0.0开始,您可以使用process
"unhandledRejection"
事件:
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.
这些事件尚未反向移植到较旧的NodeJS版本,并且不太可能.您可以使用扩展了本地Promise API的Promise库,例如 bluebird ,它会触发与现代方法相同的事件版本.
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.
还值得一提的是,有多个Userland Promise库提供未处理的拒绝检测功能,还有更多内容,例如 bluebird (也有警告)和何时.
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.
这篇关于如何使用node.js中的本机承诺全局处理异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!