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

Share:
45,667

Related videos on Youtube

Hahnemann
Author by

Hahnemann

Updated on July 09, 2022

Comments

  • Hahnemann
    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.

  • Stephen Kuehl
    Stephen Kuehl over 7 years
    Is this still valid or have things changed?
  • Pankaj Cheema
    Pankaj Cheema over 4 years
    But I need to identify that this is exception is type of json parse @Golo Roden
  • Admin
    Admin almost 4 years
    @Pankaj Cheema Just use an if statement inside the catch block.