node.js 在 JSON.parse 期间捕获节点中的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14392110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:58:54  来源:igfitidea点击:

Catch exception in node during JSON.parse

jsonnode.jsparsingexception-handling

提问by Hahnemann

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

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

var json = JSON.parse(message);

I read this threadon 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.

我阅读了有关如何在节点中捕获异常的线程,但我仍然不确定在此语句周围包装 try 和 catch 块的正确方法是什么。我的目标是捕获异常并将错误记录到控制台,当然还可以让服务器保持活动状态。谢谢你。

回答by Golo Roden

It's all good! :-)

都很好!:-)

JSON.parseruns synchronous and does not know anything about an errparameter as is often used in Node.js. Hence, you have very simple behavior: If JSON parsing is fine, JSON.parsereturns an object; if not, it throws an exception that you can catch with try / catch, just like this:

JSON.parse同步运行,并且对errNode.js 中经常使用的参数一无所知。因此,您的行为非常简单:如果 JSON 解析正常,则JSON.parse返回一个对象;如果没有,它会抛出一个异常,你可以用它来捕获try / catch,就像这样:

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

就是这样!:-)