开发者

Uncatchable errors in node.js

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.wr开发者_JS百科ite() in a try/catch block, but no luck. It seems like the error is uncatchable.


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 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


I had the same problem with the time server example from here My clients get killed and the time server then tries to write to closed socket.

Setting an error handler does not work as the error event only fires on reception. The time server does no receiving, (see stream event documentation).

My solution is to set a handler on the stream close event.

stream.on('close', function() {
    subscribers.remove(stream);
    stream.end();
    console.log('Subscriber CLOSE: ' + subscribers.length + " total.\n");
}); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜