简体   繁体   English

Node.js - 如何以编程方式捕获警告消息

[英]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?在某些特定的情况下,如果程序员不小心, Node.js 会产生以下警告: (node:11548) MaxListenersExceededWarning: Possible EventEmitter memory leak detected ,但进程继续运行,并且在初始化期间,此消息在控制台 output 中丢失,有初始化过程可以捕获此警告消息的一种方式,以便在发生时不继续进行初始化? 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).该特定消息之所以存在,是因为通常当您超过特定 eventEmitter 的侦听器数量的默认警告级别时,这表明存在某种类型的侦听器“泄漏”,您正在以他们堆积的方式添加侦听器起来(没有正确使用它们)。 The default level for this warning is 10.此警告的默认级别为 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:如果您知道这是来自哪个 eventEmitter 并且您确信这里没有实际问题,那么您可以提高导致警告的限制:

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:您可以使用这个简单的 node.js 程序演示该问题:

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 .捕获错误的方法之一总是trycatch

You can always catch uncaught exceptions with node.js by doing您始终可以通过 node.js 捕获未捕获的异常

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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