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 
17 #include "exception_utils.hpp"
18 
19 namespace phosphor::power::regulators::exception_utils
20 {
21 
22 std::vector<std::exception_ptr> getExceptions(std::exception_ptr eptr)
23 {
24     std::vector<std::exception_ptr> exceptions;
25     internal::getExceptions(eptr, exceptions);
26     return exceptions;
27 }
28 
29 std::vector<std::string> getMessages(const std::exception& e)
30 {
31     std::vector<std::string> messages{};
32     internal::getMessages(e, messages);
33     return messages;
34 }
35 
36 namespace internal
37 {
38 
39 void getExceptions(std::exception_ptr eptr,
40                    std::vector<std::exception_ptr>& exceptions)
41 {
42     // Verify exception pointer is not null
43     if (eptr)
44     {
45         // If this exception is nested, add inner exception(s) to vector
46         try
47         {
48             std::rethrow_exception(eptr);
49         }
50         catch (const std::nested_exception& e)
51         {
52             getExceptions(e.nested_ptr(), exceptions);
53         }
54         catch (...)
55         {
56         }
57 
58         // Append this exception to vector
59         exceptions.emplace_back(eptr);
60     }
61 }
62 
63 void getMessages(const std::exception& e, std::vector<std::string>& messages)
64 {
65     // If this exception is nested, get messages from inner exception(s)
66     try
67     {
68         std::rethrow_if_nested(e);
69     }
70     catch (const std::exception& inner)
71     {
72         getMessages(inner, messages);
73     }
74     catch (...)
75     {
76     }
77 
78     // Append error message from this exception
79     messages.emplace_back(e.what());
80 }
81 
82 } // namespace internal
83 
84 } // namespace phosphor::power::regulators::exception_utils
85