xref: /openbmc/boost-dbus/include/dbus/error.hpp (revision 77e62c83)
1 // Copyright (c) Benjamin Kietzman (github.com/bkietz)
2 //
3 // Distributed under the Boost Software License, Version 1.0. (See accompanying
4 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5 
6 #ifndef DBUS_ERROR_HPP
7 #define DBUS_ERROR_HPP
8 
9 #include <dbus/dbus.h>
10 #include <dbus/element.hpp>
11 #include <dbus/message.hpp>
12 #include <boost/system/error_code.hpp>
13 #include <boost/system/system_error.hpp>
14 
15 namespace dbus {
16 
17 namespace detail {
18 
19 class error_category : public boost::system::error_category {
name() const20   const char *name() const BOOST_SYSTEM_NOEXCEPT { return "dbus.error"; }
21 
message(int value) const22   string message(int value) const {
23     if (value)
24       return "DBus error";
25     else
26       return "no error";
27   }
28 };
29 
30 }  // namespace detail
31 
get_dbus_category()32 inline const boost::system::error_category &get_dbus_category() {
33   static detail::error_category instance;
34   return instance;
35 }
36 
37 class error {
38   DBusError error_;
39 
40  public:
error()41   error() {
42     dbus_error_init(&error_);
43   }
44 
error(DBusError * src)45   error(DBusError *src) {
46     dbus_error_init(&error_);
47     dbus_move_error(src, &error_);
48   }
49 
error(dbus::message & m)50   error(dbus::message &m) {
51     dbus_error_init(&error_);
52     dbus_set_error_from_message(&error_, m);
53   }
54 
~error()55   ~error() {
56     if (is_set()) {
57       dbus_error_free(&error_);
58     }
59   }
60 
is_set() const61   bool is_set() const { return dbus_error_is_set(&error_); }
62 
63   operator const DBusError *() const { return &error_; }
64 
operator DBusError*()65   operator DBusError *() { return &error_; }
66 
67   boost::system::error_code error_code() const;
68   boost::system::system_error system_error() const;
69   void throw_if_set() const;
70 };
71 
error_code() const72 inline boost::system::error_code error::error_code() const {
73   return boost::system::error_code(is_set(), get_dbus_category());
74 }
75 
system_error() const76 inline boost::system::system_error error::system_error() const {
77   return boost::system::system_error(
78       error_code(), string(error_.name) + ":" + error_.message);
79 }
80 
throw_if_set() const81 inline void error::throw_if_set() const {
82   if (is_set()) throw system_error();
83 }
84 
85 }  // namespace dbus
86 
87 #endif  // DBUS_ERROR_HPP