Skip to content

Commit

Permalink
Use UninitializedStaticallyTypedParameterException
Browse files Browse the repository at this point in the history
Signed-off-by: Mohammad Farzan <m2_farzan@yahoo.com>
  • Loading branch information
m2-farzan committed Oct 16, 2021
1 parent 942b74c commit 4c8efe3
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
17 changes: 17 additions & 0 deletions rclcpp/include/rclcpp/exceptions/exceptions.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,23 @@ class InvalidParameterTypeException : public std::runtime_error
{}
};

/// Thrown if user attempts to create an uninitialized statically typed parameter
/**
* (see https://github.com/ros2/rclcpp/issues/1691)
*/
class UninitializedStaticallyTypedParameterException : public std::runtime_error
{
public:
/// Construct an instance.
/**
* \param[in] name the name of the parameter.
*/
RCLCPP_PUBLIC
UninitializedStaticallyTypedParameterException(const std::string & name)
: std::runtime_error("Statically typed parameter '" + name + "' must be initialized.")
{}
};

/// Thrown if parameter is already declared.
class ParameterAlreadyDeclaredException : public std::runtime_error
{
Expand Down
16 changes: 10 additions & 6 deletions rclcpp/include/rclcpp/node_impl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -220,12 +220,16 @@ Node::declare_parameter(
// get advantage of parameter value template magic to get
// the correct rclcpp::ParameterType from ParameterT
rclcpp::ParameterValue value{ParameterT{}};
return this->declare_parameter(
name,
value.get_type(),
parameter_descriptor,
ignore_override
).get<ParameterT>();
try {
return this->declare_parameter(
name,
value.get_type(),
parameter_descriptor,
ignore_override
).get<ParameterT>();
} catch (const ParameterTypeException & ex) {
throw exceptions::UninitializedStaticallyTypedParameterException(name);
}
}

template<typename ParameterT>
Expand Down
6 changes: 6 additions & 0 deletions rclcpp/test/rclcpp/test_node.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,12 @@ TEST_F(TestNode, declare_parameter_with_overrides) {
"parameter_type_mismatch", rclcpp::ParameterType::PARAMETER_INTEGER);},
rclcpp::exceptions::InvalidParameterTypeException);
}
{
// statically typed parameter must be initialized
EXPECT_THROW(
{node->declare_parameter<std::string>("static_and_uninitialized");},
rclcpp::exceptions::UninitializedStaticallyTypedParameterException);
}
{
// cannot pass an expected type and a descriptor with dynamic_typing=True
rcl_interfaces::msg::ParameterDescriptor descriptor{};
Expand Down

0 comments on commit 4c8efe3

Please sign in to comment.