My node server dies when it is unable to parse JSON in the following line:
var json = JSON.parse(message);
I read this thread on how to catch e
It's all good! :-)
JSON.parse
runs synchronous and does not know anything about an err
parameter as is often used in Node.js. Hence, you have very simple behavior: If JSON parsing is fine, JSON.parse
returns an object; if not, it throws an exception that you can catch with try / catch
, just like this:
webSocket.on('message', function (message) {
var messageObject;
try {
messageObject = JSON.parse(message);
} catch (e) {
return console.error(e);
}
// At this point, messageObject contains your parsed message as an object.
}
That's it! :-)