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

时间:2014-06-18 13:31:17

标签: javascript node.js

Node.js应用程序因setInterval中的unhanded异常而终止。我尝试通过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

1 个答案:

答案 0 :(得分:0)

程序终止,因为在setInterval()之后没有其他任何东西可以处理。在nodejs doc示例中,它创建服务器并将端口绑定到它。这就是保持应用程序运行的原因。以下是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);
});

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

相关问题