[systemd-devel] For C++ coders: dbus::Error
Carlo Wood
carlo at alinoe.com
Sat Mar 6 10:16:56 UTC 2021
Hi,
I finished an implementation of dbus::Error.
dbus::Error is derived from the POD struct ErrorConst
and has no variable members of its own.
ErrorConst is just a wrapper around sd_bus_error.
struct ErrorConst {
sd_bus_error m_error;
};
class Error : protected ErrorConst {
{
... only functions here...
};
This allows to create constexpr errors with
static initialization; for example,
static constexpr ErrorConst foo_error =
{ SD_BUS_ERROR_MAKE_CONST("org.example.name", "Error description") };
The member functions of dbus::Error support
SD_BUS_ERROR_NULL (default constructor)
sd_bus_error_copy (constructing from a ErrorConst (shared), or
from an Error that is not shared (deep copy),
assignment operator)
sd_bus_error_move (move constructor, move assignment operator)
sd_bus_error_free (destructor)
sd_bus_error_set (constructing from a name with optional message)
sd_bus_error_is_set (accessor `is_set`)
Finally it can be implicitly be converted to std::error_code!
operator std::error_code() const;
The latter is the more interesting thing that took 99% of the time
to design this ;).
You can see this in action here:
https://github.com/CarloWood/dbus-task/blob/master/tests/error_test.cxx
The idea is that when, for example, you receive a callback with
a sd_bus_error* (in the message), that it is easy converted to
a std::error_code.
For example,
int on_reply_concatenate(sd_bus_message* m, void* userdata, sd_bus_error*)
{
int is_error = sd_bus_message_is_method_error(m, nullptr);
if (is_error < 0)
THROW_ALERTC(-is_error, "sd_bus_message_is_method_error");
if (is_error)
{
sd_bus_error const* error = sd_bus_message_get_error(m);
dbus::Error dbus_error = error;
std::error_code error_code = dbus_error;
std::cout << "error_code = " << error_code << " [" << error_code.message() << "]\n";
See
https://github.com/CarloWood/dbus-task/blob/master/tests/client_side_concatenate_test.cxx
for all the context.
Regards,
Carlo Wood
More information about the systemd-devel
mailing list