Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 with how to make a C++ library behave better. Basically I'm getting 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.

That happens when the input is bad. When the input - which is coming from another application of mine via memcached - happens to be bad, I would like to handle this error. You know, gracefully. Perhaps something like, "error: input for item 15006 is bad" going to the log. Not crashing my entire JSON-string-processing task.

Is this just a badly written library or is it possible to configure it more subtly?

Edit: here's some calling 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();
like image 592
djechlin Avatar asked Jun 01 '12 15:06

djechlin


2 Answers

According to the library reference:

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

Access an object value by name, create a null member if it does not exist.

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

like image 51
K-ballo Avatar answered Sep 18 '22 10:09

K-ballo


As I see from the JsonCpp Sourceforge repo, right now assertions aren't catchable (however it seems to be in their backlog to make throwing assertions).

Then, you'll have to test if the input is valid before calling the [] operator.

A link to the source code of the newest revision (I don't know the 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

like image 26
Plexico Avatar answered Sep 19 '22 10:09

Plexico