xref: /openbmc/sdbusplus/src/exception.cpp (revision adf03547)
1 #include <sdbusplus/exception.hpp>
2 
3 #include <stdexcept>
4 #include <utility>
5 
6 namespace sdbusplus
7 {
8 namespace exception
9 {
10 
11 SdBusError::SdBusError(int error, const char* prefix, SdBusInterface* intf) :
12     error(SD_BUS_ERROR_NULL), intf(intf)
13 {
14     // We can't check the output of intf->sd_bus_error_set_errno() because
15     // it returns the input errorcode. We don't want to try and guess
16     // possible error statuses. Instead, check to see if the error was
17     // constructed to determine success.
18     intf->sd_bus_error_set_errno(&this->error, error);
19     if (!intf->sd_bus_error_is_set(&this->error))
20     {
21         throw std::runtime_error("Failed to create SdBusError");
22     }
23 
24     populateMessage(prefix);
25 }
26 
27 SdBusError::SdBusError(sd_bus_error* error, const char* prefix,
28                        SdBusInterface* intf) :
29     error(*error),
30     intf(intf)
31 {
32     // We own the error so remove the caller's reference
33     *error = SD_BUS_ERROR_NULL;
34 
35     populateMessage(prefix);
36 }
37 
38 SdBusError::SdBusError(SdBusError&& other) : error(SD_BUS_ERROR_NULL)
39 {
40     move(std::move(other));
41 }
42 
43 SdBusError& SdBusError::operator=(SdBusError&& other)
44 {
45     if (this != &other)
46     {
47         move(std::move(other));
48     }
49     return *this;
50 }
51 
52 SdBusError::~SdBusError()
53 {
54     intf->sd_bus_error_free(&error);
55 }
56 
57 const char* SdBusError::name() const noexcept
58 {
59     return error.name;
60 }
61 
62 const char* SdBusError::description() const noexcept
63 {
64     return error.message;
65 }
66 
67 const char* SdBusError::what() const noexcept
68 {
69     return full_message.c_str();
70 }
71 
72 int SdBusError::get_errno() const noexcept
73 {
74     return intf->sd_bus_error_get_errno(&this->error);
75 }
76 
77 const sd_bus_error* SdBusError::get_error() const noexcept
78 {
79     return &error;
80 }
81 
82 void SdBusError::populateMessage(const char* prefix)
83 {
84     full_message = prefix;
85     if (error.name)
86     {
87         full_message += ": ";
88         full_message += error.name;
89     }
90     if (error.message)
91     {
92         full_message += ": ";
93         full_message += error.message;
94     }
95 }
96 
97 void SdBusError::move(SdBusError&& other)
98 {
99     intf = std::move(other.intf);
100 
101     intf->sd_bus_error_free(&error);
102     error = other.error;
103     other.error = SD_BUS_ERROR_NULL;
104 
105     full_message = std::move(other.full_message);
106 }
107 
108 const char* InvalidEnumString::name() const noexcept
109 {
110     return errName;
111 }
112 
113 const char* InvalidEnumString::description() const noexcept
114 {
115     return errDesc;
116 }
117 
118 const char* InvalidEnumString::what() const noexcept
119 {
120     return errWhat;
121 }
122 
123 } // namespace exception
124 } // namespace sdbusplus
125