refactor: Don't log parse errors in JsonReader::read_or

This function is designed for cases where the key may not exist, or the
value may be invalid
This commit is contained in:
John Colvin committed 2023-12-20 11:41:06 -05:00
1 parent f64e5fe1bf
commit 08706cb75d
1 file changed
+40 -1
+40 -1
View File
@@ -37,6 +37,8 @@ class JsonReader {
template <class T>
bool read(const std::string &name, T &result) const;
template <class T>
bool try_read(const std::string &name, T &result) const;
template <class T>
bool read_one_or_more(
@@ -84,6 +86,14 @@ class JsonReader {
template <class T>
bool read(T &result) const;
/**
* Reads a json field into \p result
*
* @note Doesn't log error if read op fails (unlike `read`)
*/
template <class T>
bool try_read(T &result) const;
template <class T>
T read() const;
@@ -135,6 +145,23 @@ inline bool JsonReader::read(const std::string &name, T &result) const {
return true;
}
template <class T>
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 <class T>
inline bool JsonReader::read_one_or_more(
const std::string &name, std::vector<T> &result, bool append) const {
@@ -219,6 +246,18 @@ inline bool JsonReader::read(T &result) const {
}
}
template <class T>
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 <class T>
inline T JsonReader::read() const {
T result;
@@ -262,7 +301,7 @@ inline T JsonReader::read(const std::string &name) const {
template <class T>
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;