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

Max*_*mov 2 node.js

我用process.on "uncaughtException".有时我会多次调用它,因为不是简单的模块系统.所以我收到了警告:

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

我的代码:

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

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

var n = 12;
for (var i = n - 1; i >= 0; i--) {
    onError();
};
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*att 5

由于processEventEmitter(文档),您可以使用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;
            } 
        );
    }
};
Run Code Online (Sandbox Code Playgroud)

还要注意你所看到的只是一个警告 ; 添加尽可能多的侦听器没有问题.