diff options
Diffstat (limited to 'src/univalue/lib/univalue.cpp')
-rw-r--r-- | src/univalue/lib/univalue.cpp | 19 |
1 files changed, 14 insertions, 5 deletions
diff --git a/src/univalue/lib/univalue.cpp b/src/univalue/lib/univalue.cpp index ac6f31a5a9..051bc8eba6 100644 --- a/src/univalue/lib/univalue.cpp +++ b/src/univalue/lib/univalue.cpp @@ -110,21 +110,21 @@ bool UniValue::setObject() void UniValue::push_back(const UniValue& val_) { - if (typ != VARR) throw std::runtime_error{"JSON value is not an array as expected"}; + checkType(VARR); values.push_back(val_); } void UniValue::push_backV(const std::vector<UniValue>& vec) { - if (typ != VARR) throw std::runtime_error{"JSON value is not an array as expected"}; + checkType(VARR); values.insert(values.end(), vec.begin(), vec.end()); } void UniValue::__pushKV(const std::string& key, const UniValue& val_) { - if (typ != VOBJ) throw std::runtime_error{"JSON value is not an object as expected"}; + checkType(VOBJ); keys.push_back(key); values.push_back(val_); @@ -132,7 +132,7 @@ void UniValue::__pushKV(const std::string& key, const UniValue& val_) void UniValue::pushKV(const std::string& key, const UniValue& val_) { - if (typ != VOBJ) throw std::runtime_error{"JSON value is not an object as expected"}; + checkType(VOBJ); size_t idx; if (findKey(key, idx)) @@ -143,7 +143,8 @@ void UniValue::pushKV(const std::string& key, const UniValue& val_) void UniValue::pushKVs(const UniValue& obj) { - if (typ != VOBJ || obj.typ != VOBJ) throw std::runtime_error{"JSON value is not an object as expected"}; + checkType(VOBJ); + obj.checkType(VOBJ); for (size_t i = 0; i < obj.keys.size(); i++) __pushKV(obj.keys[i], obj.values.at(i)); @@ -213,6 +214,14 @@ const UniValue& UniValue::operator[](size_t index) const return values.at(index); } +void UniValue::checkType(const VType& expected) const +{ + if (typ != expected) { + throw std::runtime_error{"JSON value of type " + std::string{uvTypeName(typ)} + " is not of expected type " + + std::string{uvTypeName(expected)}}; + } +} + const char *uvTypeName(UniValue::VType t) { switch (t) { |