Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 703
Hahnemann Avatar asked Jan 18 '13 03:01

Hahnemann


People also ask

How do I catch a JSON parse error?

The best way to catch invalid JSON parsing errors is to put the calls to JSON. parse() to a try/catch block.

Does JSON parse throw an error?

JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.

What is JSON parser exception?

When it detects invalid JSON, it throws a JSON Parse error. For example, one of the most common typos or syntax errors in JSON is adding an extra comma separator at the end of an array or object value set.

Is JSON parse safe?

Parsing JSON can be a dangerous procedure if the JSON text contains untrusted data. For example, if you parse untrusted JSON in a browser using the JavaScript “eval” function, and the untrusted JSON text itself contains JavaScript code, the code will execute during parse time.


1 Answers

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

like image 187
Golo Roden Avatar answered Oct 06 '22 00:10

Golo Roden