views:

164

answers:

2

So I'm trying to write a simple TCP socket server that broadcasts information to all connected clients. So when a user connects, they get added to the list of clients, and when the stream emits the close event, they get removed from the client list.

This works well, except that sometimes I'm sending a message just as a user disconnects.

I've tried wrapping stream.write() in a try/catch block, but no luck. It seems like the error is uncatchable.

+7  A: 

The solution is to add a listener for the stream's 'error' event. This might seem counter-intuitive at first, but the justification for it is sound.

stream.write() sends data asynchronously. By the time that node has realized that writing to the socket has raised an error your code has moved on, past the call to stream.write, so there's no way for it to raise the error there.

Instead, what node does in this situation is emit an 'error' event from the stream, and EventEmitter is coded such that if there are no listeners for an 'error' event, the error is raised as a toplevel exception, and the process ends.

Peter Burns
+1  A: 

Peter is quite right,

and there is also another way, you can also make a catch all error handler with

process.on('uncaughtException',function(error){
// process error
})

this will catch everything which is thrown...

it's usually better to do this peter's way, if possible, however if you where writing, say, a test framework, it may be a good idea to use process.on('uncaughtException',...

here is a gist which covers (i think) all the different aways of handling errors in nodejs http://gist.github.com/636290

dominic