45

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.

Community
  • 1
  • 1
Hahnemann
  • 4,378
  • 6
  • 40
  • 64
  • Can you show this in context? What is calling this? – loganfsmyth Jan 18 '13 at 03:59
  • possible duplicate of [proper way to catch exception from javascript method JSON.parse](http://stackoverflow.com/questions/4467044/proper-way-to-catch-exception-from-javascript-method-json-parse) – L0j1k Jul 15 '14 at 16:19

1 Answers1

86

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

ma11hew28
  • 121,420
  • 116
  • 450
  • 651
Golo Roden
  • 140,679
  • 96
  • 298
  • 425