如何使用node.js中的本机承诺全局处理异常? [英] How do I handle exceptions globally with native promises in node.js?

查看:69
本文介绍了如何使用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 throws. 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库提供未处理的拒绝检测功能,还有更多内容,例如(也有警告)和

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆