Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if I already set uncaughtException event

Tags:

node.js

I use process.on "uncaughtException". And sometimes I call it several times because of not trivial module system. So I got warning:

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

My code:

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

For simulating several calls I use cycle:

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

So how to check if I allready set uncaughtException event?

like image 427
Maxim Yefremov Avatar asked Sep 16 '25 22:09

Maxim Yefremov


1 Answers

As process is an EventEmitter (docs), you can use process.listeners('uncaughtException') to retrieve an array of listeners already attached (and therefore .length to see how many you have bound).

You can also use process.removeAllListeners('uncaughtException') to remove already-bound listeners if you wanted (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;
            } 
        );
    }
};

Note also that what you're seeing is just a warning; there's no problem with adding as many listeners as you have done.

like image 199
2 revsMatt Avatar answered Sep 19 '25 12:09

2 revsMatt