Catch exception in node during JSON.parse


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 exceptions in node, but I am still not sure what is the proper way to wrap a try and catch block around this statement. My goal is to catch the exception and log an error to the console, and of course keep the server alive. Thank you.

5/23/2017 12:25:33 PM

Accepted Answer

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! :-)

6/27/2015 5:56:48 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow