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), error (_what),
line (_line) 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; using runtime_error::runtime_error;
}; };
/// Base class for all type conversion errors /// Base class for all type conversion errors
struct type_error : public error { struct type_error : public error {
using error::error; using error::error;
}; };
/// Base class for errors thrown during parsing /// Base class for errors thrown during parsing
struct parse_error : public error { struct parse_error : public error {
using error::error; using error::error;
@ -45,10 +47,17 @@ namespace json {
size_t line; size_t line;
}; };
/// Base class for errors thrown during schema validation /// Base class for errors thrown during schema validation
struct schema_error : public error { struct schema_error : public error {
using error::error; using error::error;
}; };
/// Exception class for invalid object indexing
struct key_error : public error {
key_error (std::string);
};
} }
#endif #endif

View File

@ -319,16 +319,26 @@ void
json::tree::object::insert (const std::string &_key, unique_ptr<json::tree::node> &&value) json::tree::object::insert (const std::string &_key, unique_ptr<json::tree::node> &&value)
{ m_values[_key] = move(value); } { m_values[_key] = move(value); }
//-----------------------------------------------------------------------------
const json::tree::node& json::tree::node&
json::tree::object::operator[](const std::string &key) const { json::tree::object::operator[](const std::string &key)
{
auto value = m_values.find (key); auto value = m_values.find (key);
if (value == m_values.end ()) { if (value == m_values.end ())
ostringstream ss; throw json::key_error (key);
ss << "no key: " << key;
throw json::error (ss.str()); 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; return *value->second;
} }