2014-06-18 53 views
0

Node.js應用程序因setInterval中的無效異常而終止。我嘗試通過process.on('uncaughtException',..)和域方法(參見下面的代碼)修復它。雖然處理了異常,但應用程序仍然被終止。如何防止node.js應用程序終止在setInterval中未處理的異常?

function f() { 
    throw Error('have error') 
} 
process.on('uncaughtException', function(err){ 
    console.log("process.on uncaughtException") 
}) 

var d = require('domain').create(); 
d.on('error',function(err){ 
    console.log("domain.on error") 
}) 

d.run(function(){ 
    setInterval(f, 1000) 
}) 
// program terminated and output is: domain.on error 
+1

http://nodejs.org/api/domain.html#domain_warning_don_t_ignore_errors – jgillich

+0

@ jgillich的鏈接非常重要。域不是爲了避免崩潰,它們意味着在錯誤發生之後清理並最終關閉。如果一個人死亡,你通常會使用一個進程監視器來啓動一個新進程。 – loganfsmyth

回答

0

程序終止,因爲在setInterval()之後沒有別的東西要處理。在nodejs doc示例中,它創建服務器並將端口綁定到它。這就是讓應用程序運行的原因。下面是從文檔的例子:

var d = require('domain').create(); 
d.on('error', function(er) { 
    // The error won't crash the process, but what it does is worse! 
    // Though we've prevented abrupt process restarting, we are leaking 
    // resources like crazy if this ever happens. 
    // This is no better than process.on('uncaughtException')! 
    console.log('error, but oh well', er.message); 
}); 
d.run(function() { 
    require('http').createServer(function(req, res) { 
    setInterval(f, 1000); 
    }).listen(8888); 
}); 

然後,如果你的瀏覽器指向本地主機:8888,應用程序不會終止

+0

問題是關於拋出異常。 'setInterval'定時器將使進程保持打開狀態,就像服務器一樣。 – loganfsmyth

+0

setInterval()不會讓應用程序繼續運行。當nodejs達到最後時,它會剛剛退出,除非你將它綁定到端口並像例 – Ben

+0

一樣聽你的意思是說如果有異常?一個只有setInterval的程序不會僅僅關閉。 – loganfsmyth

相關問題