-
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
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
No-throw json::value() #1733
Comments
This already works, unless you're unsure if FWIW, your code should be something like |
That is actually exactly the case. When the JSON-file (i.e. the configuration) is empty, |
What would your code do if the proposed default value does not match the existing value: json j;
j["device_id"] = 10;
auto id = j.contains("device_id") ? j.value("device_id", "") : ""; (This currently throws: |
I might be missing your point, but I'd consider that a programmer error; i.e. mixing up types. I'd expect it to return the provided default value as that is what I'm asking for. Had I wanted an integer as a default value, then I'd call value with an int as a default value. |
The thing is: you do not know which value is actually stored in the object. You may have expected a string and provided |
You're right in that I don't know what value has actually been stored, but I'm 100% sure what the application expects, which is exactly why the ability to provide a default value without the possibility of an exceptions would be such a good thing. If the application expects a string but a number has been stored, then there's a mismatch between expected and actual data. This could for example happen when a user manually edits a JSON configuration and enters What is the correct behavior in this case? I'd say it is up to the application to decide; either 1) throw an exception (as it currently does), catch it and handle it by using a default value, or 2) catch the exception, log and exit. In my case - an embedded system with no screen or keyboard - using default values is always the preferred option instead of entering a boot-loop due to bad configuration. If this still doesn't makes sense to you, feel free to close this issue, I'll fallback to writing a wrapper for reading values. |
My point is that even your "no-throw" auto id = cfg.is_object() ? cfg.value("device_id", "") : ""; as this makes it explicit that you are OK with |
Currently, it's a must to write code like this to prevent exceptions in the case optional values are omitted from the underlying data:
A more streamlined version would be like this, specifying no-throw, similar to
json::parse
:Allowing
value()
to take anallow_exception
, same asjson::parse
would reduce boiler place code and also meet user expectations; we're providing a default value, but instead of returning that,value()
throws an exception.Thoughts?
The text was updated successfully, but these errors were encountered: