diff --git a/json/except.cpp b/json/except.cpp index 430e597e..6019ffd3 100644 --- a/json/except.cpp +++ b/json/except.cpp @@ -26,3 +26,9 @@ json::parse_error::parse_error (const std::string &_what, size_t _line): error (_what), line (_line) { ; } + + +//----------------------------------------------------------------------------- +json::key_error::key_error (std::string _what): + error (std::move (_what)) +{ ; } diff --git a/json/except.hpp b/json/except.hpp index ec9be0b9..8d7ffb5b 100644 --- a/json/except.hpp +++ b/json/except.hpp @@ -31,11 +31,13 @@ namespace json { using runtime_error::runtime_error; }; + /// Base class for all type conversion errors struct type_error : public error { using error::error; }; + /// Base class for errors thrown during parsing struct parse_error : public error { using error::error; @@ -45,10 +47,17 @@ namespace json { size_t line; }; + /// Base class for errors thrown during schema validation struct schema_error : public error { using error::error; }; + + + /// Exception class for invalid object indexing + struct key_error : public error { + key_error (std::string); + }; } #endif diff --git a/json/tree.cpp b/json/tree.cpp index 0f6a601e..359728de 100644 --- a/json/tree.cpp +++ b/json/tree.cpp @@ -319,15 +319,25 @@ void json::tree::object::insert (const std::string &_key, unique_ptr &&value) { m_values[_key] = move(value); } - -const json::tree::node& -json::tree::object::operator[](const std::string &key) const { +//----------------------------------------------------------------------------- +json::tree::node& +json::tree::object::operator[](const std::string &key) +{ auto value = m_values.find (key); - if (value == m_values.end ()) { - ostringstream ss; - ss << "no key: " << key; - throw json::error (ss.str()); - } + if (value == m_values.end ()) + throw json::key_error (key); + + return *value->second; +} + + +//----------------------------------------------------------------------------- +const json::tree::node& +json::tree::object::operator[](const std::string &key) const +{ + auto value = m_values.find (key); + if (value == m_values.end ()) + throw json::key_error (key); return *value->second; }