More graceful error handling in C ++ library - jsoncpp

I'm not sure if this will be a specific thing with jsoncpp or a general paradigm on how to make the C ++ library behave better. Basically I get this trace:

imagegeneratormanager.tsk: src/lib_json/json_value.cpp:1176: const Json::Value& Json::Value::operator[](const char*) const: Assertion `type_ == nullValue || type_ == objectValue' failed. 

This happens when the input is bad. When the input - which comes from another application of mine through memcached - turns out to be bad, I would like to handle this error. You know, gracefully. Perhaps something like "error: entry for element 15006 is bad", going to the log. Not all my JSON string processing task crashes.

Is it just a poorly written library, or can you customize it more finely?

Edit: here is the call code:

 Json::Value root; Json::Reader reader; succeeded = reader.parse(jsonString, root); if(!succeeded) { throw std::runtime_error(std::string("Failed to parse JSON for key ") + emailInfoKey.str()); } std::string userEmail = root.get("userId", "").asString(); std::string bodyFilePath = root.get("bodyFilePath", "").asString(); std::string msgId = root.get("msgId", "").asString(); 
+6
source share
2 answers

According to the library reference:

Value and Json :: Value :: operator [] (const StaticString and key)

Access the value of the object by name, create a null element if it does not exist.

It seems you are trying to call operator[] on a non-object, like an integer or a string ( get internally uses operator[] ). You are violating the precondition of the function and its error on your side of the code, not in the library. You can check if the Json::Value object is an object before accessing it as such using isObject() .

+4
source

As I can see from the JsonCpp Sourceforge repo, the statements aren’t tricky right now (however, they seem to make throw statements in their lag).

Then you will need to check if the input is valid before calling the [] operator.

Link to the source code of the latest version (I don’t know what version you have). See Line 1141: http://jsoncpp.svn.sourceforge.net/viewvc/jsoncpp/trunk/jsoncpp/src/lib_json/json_value.cpp?revision=249&view=markup

+4
source

Source: https://habr.com/ru/post/917197/


All Articles