Nodejs:如何捕捉net.createServer.on(“data”,…)中的exception?

我有一个标准的套接字服务器(无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",...)

也许我需要到达sockets,而不是c (连接),虽然我不知道如何。

我在Node 0.6.9上

谢谢。

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

你应该自己去捕捉exception。 在连接或服务器对象上都没有事件可以让你按照你所描述的方式处理exception。 您应该添加exception处理逻辑到您的事件处理程序中,以避免服务器崩溃,如下所示:

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