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

查看:21
本文介绍了如何使用 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.parse throw s 时,我得到无效的 JSON 导致无提示失败.一般来说,我必须记住为我的代码中的每个承诺添加一个 .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?

推荐答案

编辑

我们终于在 Node.js 15 中解决了这个问题,花了 5 年的时间,但原生承诺拒绝现在表现得像未捕获的异常 - 所以只需添加一个 process.on('uncaughtException'处理程序.

从 io.js 1.4 和 Node 4.0.0 开始,您可以使用 process unhandledRejection" 事件:

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.

这些事件尚未向后移植到旧版本的 NodeJS,而且不太可能.您可以使用扩展本机承诺 API 的承诺库,例如 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.

还值得一提的是,有几个用户态承诺库提供了未处理的拒绝检测功能以及更多功能,例如 (也有警告)和 .

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屋!

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