diff --git a/src/lib/io/JsonReader.h b/src/lib/io/JsonReader.h index cdc8970cb..e05e565eb 100644 --- a/src/lib/io/JsonReader.h +++ b/src/lib/io/JsonReader.h @@ -37,6 +37,8 @@ class JsonReader { template bool read(const std::string &name, T &result) const; + template + bool try_read(const std::string &name, T &result) const; template bool read_one_or_more( @@ -84,6 +86,14 @@ class JsonReader { template bool read(T &result) const; + /** + * Reads a json field into \p result + * + * @note Doesn't log error if read op fails (unlike `read`) + */ + template + bool try_read(T &result) const; + template T read() const; @@ -135,6 +145,23 @@ inline bool JsonReader::read(const std::string &name, T &result) const { return true; } +template +inline bool JsonReader::try_read(const std::string &name, T &result) const { + if (!json_ || !json_->is_object()) { + return false; + } + auto it = json_->find(name); + if (it == json_->end()) { + return false; + } + try { + it->get_to(result); + } catch (...) { + return false; + } + return true; +} + template inline bool JsonReader::read_one_or_more( const std::string &name, std::vector &result, bool append) const { @@ -219,6 +246,18 @@ inline bool JsonReader::read(T &result) const { } } +template +inline bool JsonReader::try_read(T &result) const { + try { + json_->get_to(result); + return true; + } catch (...) { + const auto j_str = json_->dump(2); + LOG(md, Error, "Exception parsing json:\n{}", j_str); + return false; + } +} + template inline T JsonReader::read() const { T result; @@ -262,7 +301,7 @@ inline T JsonReader::read(const std::string &name) const { template inline bool JsonReader::read_or( const std::string &name, T &result, T default_value) const { - if (read(name, result)) { + if (try_read(name, result)) { return true; } result = default_value;