如何以可读的方式处理nlohmannException.type_error

问题描述 投票:0回答:1

我正在使用 nlohmann json 来解析

config.json
文件。该文件将由使用我的代码的其他开发人员修改。

try {
        conf.x1 = data.at("x1");
        conf.x2 = data.at("x2");
        // ...
        conf.xN = data.at("xN");
} catch (const nlohmann::json::out_of_range &e) {
        std::cerr << "Error. " << e.what() << std::endl;
        return std::nullopt;
} catch (const nlohmann::json::type_error &e) {
        std::cerr << "Error. " << e.what() << std::endl;
        return std::nullopt;
}
  1. 当遇到
    nlohmann::json::out_of_range
    异常时,
    e.what()
    会显示:
    [json.exception.out_of_range.403] key 'x1' not found
  2. 当遇到
    nlohmann::json::type_error
    异常时,是
    [json.exception.type_error.302] type must be number, but is string

在第一种情况下,它很容易告诉用户值

x1
是预期的,但没有找到,即使我在整个博客上
catch
。对于第二种情况,没有提示,这导致了错误,迫使用户在整个文件中进行搜索。
我想编写一个执行 try-catch 的函数,例如

xN

,但是返回值不同,我想可以通过模板或为每种类型编写一个函数来解决。

由于这使代码变得复杂,我首先想找出是否有更简单的替代方案,类似于 

int read_data(const std::string key)

异常。

    

c++ json config nlohmann-json
1个回答
0
投票

FAQ

中它说要定义out_of_range。进一步阅读

由于此全局上下文的代价是每个 JSON 值存储一个额外的指针以及维护父关系的运行时开销,因此默认情况下禁用扩展诊断。但是,可以通过在包含 json.hpp 之前将预处理器符号 JSON_DIAGNOSTICS 定义为 1 来启用它们。

因此,在调试时,在包含之前添加定义。在我们的例子中,我们只需

JSON_DIAGNOSITCS
获取调试标志来决定是否需要诊断。

#ifdef


© www.soinside.com 2019 - 2024. All rights reserved.