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.
The best way to catch invalid JSON parsing errors is to put the calls to JSON. parse() to a try/catch block.
JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.
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.
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.
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! :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With