Catch exception in node during JSON.parse
45,667
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! :-)
Related videos on Youtube
Author by
Hahnemann
Updated on July 09, 2022Comments
-
Hahnemann almost 2 years
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.
-
loganfsmyth over 11 yearsCan you show this in context? What is calling this?
-
L0j1k almost 10 yearspossible duplicate of proper way to catch exception from javascript method JSON.parse
-
-
Stephen Kuehl over 7 yearsIs this still valid or have things changed?
-
Pankaj Cheema over 4 yearsBut I need to identify that this is exception is type of json parse @Golo Roden
-
Admin almost 4 years@Pankaj Cheema Just use an if statement inside the catch block.