gpt4 book ai didi

node.js - 如何检查我是否已经设置了 uncaughtException 事件

转载 作者:搜寻专家 更新时间:2023-11-01 00:25:52 24 4
gpt4 key购买 nike

我使用 process.on "uncaughtException"。有时我会多次调用它,因为它不是微不足道的模块系统。所以我得到警告:

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.

我的代码:

var onError = function (){
if (true) // how to check if I allready set uncaughtException event?
{
process.on ("uncaughtException", function (err) {
console.log ("uncaughtException");
throw err;
}
);
}
};

为了模拟多个调用,我使用循环:

var n = 12;
for (var i = n - 1; i >= 0; i--) {
onError();
};

那么如何检查我是否已经设置了 uncaughtException 事件?

最佳答案

由于 process 是一个 EventEmitter ( docs ),您可以使用 process.listeners('uncaughtException') 来检索数组已经附加的听众数量(因此 .length 可以查看您绑定(bind)了多少)。

如果需要,您还可以使用 process.removeAllListeners('uncaughtException') 删除已经绑定(bind)的监听器 (docs)。

var onError = function (){
if (process.listeners('uncaughtException').length == 0) // how to check if I allready set uncaughtException event?
{
process.on ("uncaughtException", function (err) {
console.log ("uncaughtException");
throw err;
}
);
}
};

另请注意,您看到的只是一个警告;添加尽可能多的听众没有问题

关于node.js - 如何检查我是否已经设置了 uncaughtException 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17897883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com