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.
It’s all good! 🙂
JSON.parseruns synchronous and does not know anything about anerrparameter as is often used in Node.js. Hence, you have very simple behavior: If JSON parsing is fine,JSON.parsereturns an object; if not, it throws an exception that you can catch withtry / catch, just like this:That’s it! 🙂