Skip to content

(core): add helper function to ease error handling in boost::property_tree

Flavien BRIDAULT requested to merge 106-core-booleans-config-parsing-2 into dev

Description

This adds a new function to ease error handling in boost::property_tree.

Here the problem, in the following tree:

boost::property_tree::ptree config;
config.put("test.yes", "foo");
config.put("test.true", "true");

Those two calls will return the default value:

config.get<bool>("test.yes", false);
config.get<bool>("test.doesntexist", false);

When we switch from ConfigurationElement to boost::property_tree, we chose to ignore bad values, but actually, this may be a flaw. I propose to make a difference and use a template function that:

  • returns the value if the path is set
  • returns the default value if the path is not set
  • throws if the path is set but the value is incorrect and displays a log error

Throwing is the best option, because by default it will break, allowing the developer to quickly spot the error, but it can be caught if the error is acceptable. Even that in this case, it might be better to stick with config.get(...) (the only difference is that you will just get an error in the log)

How to test it?

Run coreTest, and/or experiment in a service configuration method.

Some results

core::runtime::get_ptree_value(config, "test.true", false); // returns true
core::runtime::get_ptree_value(config, "test.yes", false);  // throws
core::runtime::get_ptree_value(config, "test.foo", false);  // returns false
core::runtime::get_ptree_value(config, "test.foo", true);  // returns true
core::runtime::get_ptree_value(config, "test.true", 42);  // throws because it implicitly request an integer
Edited by Flavien BRIDAULT

Merge request reports