简体   繁体   中英

Node.js - How to programatically catch warning messages

In some specific ocasions, if the programmer is not careful, Node.js generate the following warning: (node:11548) MaxListenersExceededWarning: Possible EventEmitter memory leak detected , but the process continue running, and this message gets lost in the console output during initialization, there's a way the initialization process can catch this warning message in order to not proceed the initialization if it occurs? Thanks in advance.

That specific message is there because often times when you exceed the default warning level for the number of listeners to a specific eventEmitter this is a sign that there's some sort of "leak" of listeners where you're adding listeners in a way that they pile up (not using them correctly). The default level for this warning is 10.

So, it's generally worth debugging the cause of this warning and understanding whether it's a legit warning (a sign of a real problem) or a false warning (not caused by an actual problem).

If you know which eventEmitter this is coming from and you've convinced yourself that there is not an actual problem here, then you can raise the limit that causes the warning with:

emitter.setMaxListeners(30);    // pick whatever limit is appropriate

You can see the doc for that method here .


You can catch this particular warning with this code :

process.on('warning', warningInfo => {
   // examine the warning here and decide what to do
   console.log(warningInfo);
});

You can demonstrate the issue with this simple node.js program:

const EventEmitter = require('events');

const e = new EventEmitter();

// create one more listener for the same event than the default 
// warning limit
for (let i = 0; i < 11; i++) {
    e.on("greeting", () => {
        console.log("greeting");
    });
}

// listen for the warning
process.on('warning', info => {
    console.log(info);
});

One of the ways of catching errors is always try and catch .

You can always catch uncaught exceptions with node.js by doing

process.on('uncaughtException', err => {
  console.error('There was an uncaught error', err)
  process.exit(1) //mandatory (as per the Node.js docs)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM