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

Error Code Return #1386

Closed
dhruveshg opened this issue Dec 7, 2018 · 3 comments
Closed

Error Code Return #1386

dhruveshg opened this issue Dec 7, 2018 · 3 comments

Comments

@dhruveshg
Copy link

dhruveshg commented Dec 7, 2018

  • No error code is returned and it crashes if the "key" is not found. I am new to this library, am I missing something? Could it return error code, or the only way to avoid crashing is to use exception handling?

json jProfile;
std::ifstream f(profileFile);
f >> jProfile;
jProfile.at("CONFIG").at(std::to_string(1)).get_to(configFileName);

@gregmarr
Copy link
Contributor

gregmarr commented Dec 7, 2018

If you don't know if the keys you are looking for are there, you either need to check first, using things like find(), or use the value() functions that take default values to return if the element is not found.

@RPGillespie6
Copy link

RPGillespie6 commented Dec 7, 2018

.at() throws an json::out_of_range if the key is not found. Also, this code with throw json::parse_error if profileFile is not valid json. You should wrap the whole thing with:

try {
    json jProfile;
    std::ifstream f(profileFile);
    f >> jProfile;
    jProfile.at("CONFIG").at(std::to_string(1)).get_to(configFileName);
} catch (json::exception & ex) {
    cout << "Uh oh, I messed up: " << ex.what() << endl;
}

If you don't want to do exception handling, then you have to do:

if (jProfile.count("CONFIG") && jProfile["CONFIG"].count("1"))
   jProfile.at("CONFIG").at(std::to_string(1)).get_to(configFileName);

@dhruveshg
Copy link
Author

Thanks, I understand the implementation better now.

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

No branches or pull requests

3 participants