Nodejs:如何在net.createServer.on(“data”,...)中捕获异常?

时间:2012-09-26 18:39:15

标签: sockets node.js exception-handling

我有一个标准的socket-server(NO HTTP)设置如下(设计):

var server = net.createServer(function(c) { //'connection' listener
  c.on('data', function(data) {
    //do stuff here
    //some stuff can result in an exception that isn't caught anywhere downstream, 
    //so it bubbles up. I try to catch it here. 
    //this is the same problem as just trying to catch this: 
    throw new Error("catch me if you can");
  });
}).listen(8124, function() { //'listening' listener
   console.log('socket server started on port 8124,');
});

现在问题是我有一些代码抛出了根本没有捕获的错误,导致服务器崩溃。作为最后一项措施,我想在这个级别上抓住它们,但是我尝试过的任何事情都失败了。

  • server.on("error",....)
  • c.on("error",...)

也许我需要进入套接字而不是c(连接),虽然我不确定如何。

我在Node 0.6.9上

感谢。

2 个答案:

答案 0 :(得分:3)

process.on('uncaughtException',function(err){
   console.log('something terrible happened..')
})

答案 1 :(得分:0)

你应该自己抓住例外。连接或服务器对象上没有任何事件可以让您按照描述的方式处理异常。您应该在事件处理程序中添加异常处理逻辑,以避免服务器崩溃,如下所示:

c.on('data', function(data) {
  try {
     // even handling code
  }
  catch(exception) {
    // exception handling code
  }
相关问题