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

时间:2013-07-27 12:36:12

标签: node.js

我使用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事件?

1 个答案:

答案 0 :(得分:5)

由于processEventEmitterdocs),您可以使用process.listeners('uncaughtException')检索已经附加的侦听器数组(因此.length可以查看你绑定了多少人。)

如果需要,您还可以使用process.removeAllListeners('uncaughtException')删除已绑定的侦听器(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;
            } 
        );
    }
};

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

相关问题