json: add key_error exception class

This commit is contained in:
Danny Robson 2015-03-18 15:40:16 +11:00
parent 800937086b
commit 47cc2adfab
3 changed files with 33 additions and 8 deletions

View File

@ -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))
{ ; }

View File

@ -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

View File

@ -319,15 +319,25 @@ void
json::tree::object::insert (const std::string &_key, unique_ptr<json::tree::node> &&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;
}