[英]Node.js - How to programatically catch warning messages
在某些特定的情況下,如果程序員不小心, Node.js 會產生以下警告: (node:11548) MaxListenersExceededWarning: Possible EventEmitter memory leak detected
,但進程繼續運行,並且在初始化期間,此消息在控制台 output 中丟失,有初始化過程可以捕獲此警告消息的一種方式,以便在發生時不繼續進行初始化? 提前致謝。
該特定消息之所以存在,是因為通常當您超過特定 eventEmitter 的偵聽器數量的默認警告級別時,這表明存在某種類型的偵聽器“泄漏”,您正在以他們堆積的方式添加偵聽器起來(沒有正確使用它們)。 此警告的默認級別為 10。
因此,通常值得調試此警告的原因並了解它是合法警告(真正問題的跡象)還是錯誤警告(不是由實際問題引起的)。
如果您知道這是來自哪個 eventEmitter 並且您確信這里沒有實際問題,那么您可以提高導致警告的限制:
emitter.setMaxListeners(30); // pick whatever limit is appropriate
您可以在此處查看該方法的文檔。
您可以使用此代碼捕獲此特定警告:
process.on('warning', warningInfo => {
// examine the warning here and decide what to do
console.log(warningInfo);
});
您可以使用這個簡單的 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);
});
捕獲錯誤的方法之一總是try
和catch
。
您始終可以通過 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.