2014-06-18 56 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

相关问题