1 /**
2  * Copyright © 2020 IBM Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #pragma once
17 
18 #include "action.hpp"
19 
20 #include <exception>
21 #include <string>
22 
23 namespace phosphor::power::regulators
24 {
25 
26 /**
27  * @class ActionError
28  *
29  * An error that occurred while executing an action.
30  *
31  * This exception describes the action that failed.  If the cause of the failure
32  * was another exception (such as I2CException), the other exception can be
33  * nested inside the ActionError using std::throw_with_nested().
34  */
35 class ActionError : public std::exception
36 {
37   public:
38     // Specify which compiler-generated methods we want
39     ActionError() = delete;
40     ActionError(const ActionError&) = default;
41     ActionError(ActionError&&) = default;
42     ActionError& operator=(const ActionError&) = default;
43     ActionError& operator=(ActionError&&) = default;
44     virtual ~ActionError() = default;
45 
46     /**
47      * Constructor.
48      *
49      * @param action action that was executed
50      * @param error error message
51      */
ActionError(const Action & action,const std::string & error="")52     explicit ActionError(const Action& action, const std::string& error = "") :
53         message{"ActionError: " + action.toString()}
54     {
55         if (error.length() > 0)
56         {
57             message += ": ";
58             message += error;
59         }
60 
61         // Note: Do not store a reference or pointer to the Action.  It may be
62         // destructed (out of scope) before the exception is caught.
63     }
64 
65     /**
66      * Returns the description of this error.
67      *
68      * @return error description
69      */
what() const70     const char* what() const noexcept override
71     {
72         return message.c_str();
73     }
74 
75   private:
76     /**
77      * Message describing this exception.
78      */
79     std::string message{};
80 };
81 
82 } // namespace phosphor::power::regulators
83