2013-07-27 66 views
2

我使用process.on "uncaughtException"。有時我會因爲不平凡的模塊系統而多次調用它。所以我就警告:如何檢查我是否已經設置了uncaughtException事件

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

我的代碼:

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

爲了模擬幾個電話我使用週期:

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

因此,如何檢查,如果我媒體鏈接設置uncaughtException事件?

+0

爲什麼綁定多個uncaughtException監聽器?只需在app.js的開頭綁定一次即可。 –

回答

5

由於processEventEmitterdocs),你可以使用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; 
      } 
     ); 
    } 
}; 

還要注意的是,你看到的只是一個警告;有沒有問題添加儘可能多的聽衆,因爲你已經做了。

+0

是的,這是一個警告,但如果多次綁定相同的偵聽器,則不會在事件中多次調用它? –

+0

@SnowBlind:是的,它會多次觸發。 – Matt

+1

我不認爲這就是OP想要發生的事情。只是一個頭。 –

相關問題