Easier way to handle exceptions instead of try/catch every line? #2993
-
Hi, I'm wondering if there is a better way of handling exceptions in a situation like this: profile.url = j.at("url").get<std::string>();
profile.created_at = j.at("created_at").get<std::string>();
profile.name = j.at("name").get<std::string>();
profile.username = j.at("username").get<std::string>(); Since I cant guarantee that all the lines will be strings(might be null, etc) is there a way for them to fallback to just returning an empty string or json null, instead of having to wrap each line in a try/catch block? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
If you know the value is either std::string get_value(const json& j, const std::string& key, const std::string& default_value)
{
if (j.contains("key") && j["key"].is_string())
{
return j["key"];
}
return default_value;
} |
Beta Was this translation helpful? Give feedback.
-
Yeah that works for me. I dont even know if the value will even be there but this gives me some ideas of how to handle it. Thanks! |
Beta Was this translation helpful? Give feedback.
If you know the value is either
null
or a string, then you can use thevalue
function. Note it throws if the actual value is notnull
, but does not fit the default value. If you cannot rule out such situations, I guess the best would be a helper function. Something like