Javascript 如何防止node.js应用程序因setInterval中未处理的异常而终止?

Javascript 如何防止node.js应用程序因setInterval中未处理的异常而终止?,javascript,node.js,Javascript,Node.js,Node.js应用程序因setInterval中的意外异常而终止。我试图通过process.on('uncaughtException',..)和域方法(参见下面的代码)来修复它。尽管已处理异常,但应用程序仍被终止 function f () { throw Error('have error') } process.on('uncaughtException', function(err){ console.log("process.on uncaughtException")

Node.js应用程序因setInterval中的意外异常而终止。我试图通过process.on('uncaughtException',..)和域方法(参见下面的代码)来修复它。尽管已处理异常,但应用程序仍被终止

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

程序终止,因为在setInterval()之后没有其他要处理的内容。在nodejs文档示例中,它创建服务器的端口并将端口绑定到服务器。这就是保持应用程序运行的原因。以下是文档中的示例:

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);
});

然后,如果您将浏览器指向localhost:8888,则应用程序不会终止

@jgillich的链接非常重要。域并不是为了避免崩溃,而是作为错误后清理和正确关闭的最后一行。如果一个进程死亡,您通常会使用进程监视器启动一个新进程。问题是抛出异常
setInterval
计时器会像服务器一样保持进程打开。setInterval()不会保持应用程序运行。当nodejs到达末尾时,它将退出,除非您将其绑定到端口并像示例中那样进行侦听。您的意思是如果有异常?只有setInterval的程序不会只是关闭。f()中的异常会导致setInterval()停止,但如果您作为服务器运行,它会保持应用程序运行。尝试放置console.log()而不是抛出错误(),setInterval()将保持运行正常。很抱歉,从您将其表述为终止的方式来看,因为它后面没有任何内容,听起来好像您认为setInterval根本无法保持应用程序的打开状态。现在我看到您在说,在计时器中抛出异常会将计时器从事件循环中清除,所以节点不会保持打开状态。