Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.write() in a try/catch block, but no luck. It seems like the error is uncatchable.

like image 935
Peter Burns Avatar asked May 23 '10 21:05

Peter Burns


People also ask

How many types of errors are there in node JS?

In general, Node. js errors are divided into two distinct categories: operational errors and programmer errors.

What is type error in node JS?

The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. A TypeError may be thrown when: an operand or argument passed to a function is incompatible with the type expected by that operator or function; or.


1 Answers

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.

like image 78
Peter Burns Avatar answered Nov 16 '22 01:11

Peter Burns