未捕获 Simdjson 库的 C++ 异常

c++ exception not caught for simdjson library

本文关键字:C++ 异常 库的 Simdjson      更新时间:2023-10-16

我正在尝试使用 simdjson 库:https://github.com/simdjson/simdjson#documentation

但是,我需要解析的 json 来自 websocket 连接,并不总是包含相同的键。因此,有时尝试从解析的 json 对象中按键提取值会引发异常:

terminate called after throwing an instance of 'simdjson::simdjson_error'
what():  The JSON field referenced does not exist in this object.
Aborted (core dumped)

下面尝试使异常处理正常工作的示例代码:

#include <iostream>
#include <string>
#include <chrono>
#include "simdjson.h"
using namespace std;
using namespace simdjson;
int main() {
auto cars_json = R"( [
{ "make": "Toyota", "model": "Camry",  "year": 2018, "tire_pressure": [ 40.1, 39.9, 37.7, 40.4 ] },
{ "make": "Kia",    "model": "Soul",   "year": 2012, "tire_pressure": [ 30.1, 31.0, 28.6, 28.7 ] },
{ "make": "Toyota", "model": "Tercel", "year": 1999, "tire_pressure": [ 29.8, 30.0, 30.2, 30.5 ] }
] )"_padded;
simdjson::error_code error_c;
dom::parser  parser;
dom::object  doc;
dom::element elem;
const char* value;
doc = parser.parse(cars_json);
try
{
doc["clOrdID"].get<const char*>().tie(value, error_c);
} 
catch (simdjson_error e)
{
cout << 1 << endl;
}
return 0;
}

我已经阅读了有关库错误处理的文档: https://github.com/simdjson/simdjson/blob/master/doc/basics.md#error-handling

但是,使用 try-catch 块和上述文档中描述的错误处理方法仍会导致程序退出。我对 c++ 编程非常陌生,因此也是该语言中的异常处理 - 有关如何从此库中捕获任何异常的任何指导将不胜感激!

首先,您应该将parser.parse(cars_json);移动到try / catch块中,以便捕获解析器异常

try {
doc = parser.parse(cars_json);
} catch (simdjson::simdjson_error e) {
cout << e.what() << endl;
}

然后您可能会意识到parser不会返回simdjson::dom::object而是返回simdjson::dom::array

下面是转换为const char*的更新示例

const char* value;
try {
auto root = parser.parse(cars_json);
cout << "root: " << root.type() << endl;
auto car = root.at(0);
if(car["make"].is_string()){
cout << "first car: " << car["make"] << endl;
}
//check non-existing element
if(car["foo"].is_string()){
// exception won't be thrown
}
std::string_view sv = root.at(1)["model"];
cout << "string view: " << sv << endl;
//conversion to const char*
value = std::string(sv).c_str();
cout << "const char: " << value << endl;

} catch (const simdjson::simdjson_error &e) {
cout << e.what() << endl;
}

输出应为:

root: array
first car: "Toyota"
string view: Soul
const char: Soul

这是一个老问题,但我在使用发布v0.9.6时遇到了同样的问题(来自文档推荐的 CMake 安装(

唯一的其他答案永远不会真正使代码工作。

我升级到v3.1.6,这是撰写此答案时的最新内容,然后删除了我的CMake文件夹,并且此错误已修复。