cliss/accidentalbot — pull request #25 by galambalazs (2014-06-29 13:42:03+00:00)
Title: Catch socket errors and JSON.parse exceptions

This is to solve the problems mentioned in the show.

You indeed missed to catch exceptions coming from sockets, but they are a little bit hidden and not 100% straightforward, if you're new to node.

Basically the library you're using (`ws`) to handle `WebSockets` is implementing an `EventEmitter` interface. This is a standard citizen in the node.js world.

You can publish & subscribe to events.

BUT there is a special event named `error` which - if emitted and there's no listener for it - will terminate your program (basically an exception is thrown).

If you *do* have an `.on('error', ...)` listener, however, there's no exception thrown and you can just log the error for later.

*From the documentation:*

> When an EventEmitter instance experiences an error, the typical action is to emit an 'error' event. Error events are treated as a special case in node. If there is no listener for it, then the default action is to print a stack trace and exit the program.
> http://nodejs.org/api/events.html#events_class_events_eventemitter

The JSON.parse try/catch is just good practice, because it's another data from the outside world, and JSON.parse is known to throw exceptions when it fails to parse the text.