Catch exception in node during JSON.parse

后端 未结 1 333
再見小時候
再見小時候 2021-02-03 18:08

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 e

相关标签:
1条回答
  • 2021-02-03 18:49

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

    0 讨论(0)
提交回复
热议问题