Skip to content

Easier way to handle exceptions instead of try/catch every line? #2993

Answered by nlohmann
dominique120 asked this question in Q&A
Discussion options

You must be logged in to vote

If you know the value is either null or a string, then you can use the value function. Note it throws if the actual value is not null, 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

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;
}

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by dominique120
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants