Nodejs: How to catch exception in net.createServer.on("data",...)?

I've got a standard socket-server (NO HTTP) setup as follows (contrived):

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

Now the thing is I've got some code throwing errors that aren't catched at all, crashing the server. As a last measure I'd like to catch them on this level, but anything I've tried fails.

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

Perhaps I need to get to the socket instead of c (the connection), although I'm not sure how.

I'm on Node 0.6.9

Thanks.

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

You should catch the Exceptions yourself. There is no event on either connection or server objects which would allow you to handle exception the way you described. You should add exception handling logic into your event handlers to avoid server crash like this:

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