Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add key name to exception #160

Closed
Furcube opened this issue Dec 19, 2015 · 1 comment
Closed

add key name to exception #160

Furcube opened this issue Dec 19, 2015 · 1 comment

Comments

@Furcube
Copy link

Furcube commented Dec 19, 2015

I use library to deserialize json to class.
Seem to be simple like this:

class test {
public:
  std::string str;
  int i;

  test(const json & json) :
          str(json.at("str").get<std::string>()),
          i(json.at("i"))) {
  }
};

But at will throw out_of_range without actually telling what it could not find. Makes deserialization without touching json.hpp much harder that it could be.

It would be good for exceptions to be more verbose.

Not sure that it will work in all cases, but it works for mine. I've changed json.hpp like this:

diff --git a/src/json.hpp b/src/json.hpp
index 9de73dd..a5d74b9 100644
--- a/src/json.hpp
+++ b/src/json.hpp
@@ -2686,7 +2686,11 @@ class basic_json
         // at only works for objects
         if (is_object())
         {
-            return m_value.object->at(key);
+               try {
+                       return m_value.object->at(key);
+               } catch(const std::out_of_range & e) {
+                       throw std::out_of_range("can't find \"" + key + '"');
+               }
         }
         else
         {
@@ -2724,7 +2728,11 @@ class basic_json
         // at only works for objects
         if (is_object())
         {
-            return m_value.object->at(key);
+               try {
+                       return m_value.object->at(key);
+               } catch(const std::out_of_range & e) {
+                       throw std::out_of_range("can't find \"" + key + '"');
+               }
         }
         else
         {

And now I can just log exception and tell what is missing.

@nlohmann
Copy link
Owner

Hi @Furcube, I changed the exceptions accordingly and also overworked the test suite and documentation. I hope you like it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants