在JSON.parse期间在节点中捕获异常 [英] Catch exception in node during JSON.parse

查看:297
本文介绍了在JSON.parse期间在节点中捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法在以下行中解析JSON时,我的节点服务器死掉了:

My node server dies when it is unable to parse JSON in the following line:

var json = JSON.parse(message);

我阅读了此线程关于如何在节点中捕获异常的信息,但是我仍然不确定围绕该语句包装try and catch块的正确方法是什么.我的目标是捕获异常并将错误记录到控制台,当然还要使服务器保持活动状态.谢谢.

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.

推荐答案

一切都很好! :-)

JSON.parse同步运行,并且对Node.js中经常使用的err参数一无所知.因此,您的行为非常简单:如果JSON解析正常,则JSON.parse返回一个对象;否则,返回<0>.如果不是,它将抛出一个异常,您可以使用try / catch捕获该异常,如下所示:

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.
}

就是这样! :-)

这篇关于在JSON.parse期间在节点中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆