1 | /* |
2 | * Copyright 2016-present Facebook, Inc. |
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 | #pragma once |
18 | |
19 | #include <exception> |
20 | #include <string> |
21 | #include <type_traits> |
22 | |
23 | #include <folly/Demangle.h> |
24 | #include <folly/FBString.h> |
25 | #include <folly/Portability.h> |
26 | |
27 | namespace folly { |
28 | |
29 | /** |
30 | * Debug string for an exception: include type and what(), if |
31 | * defined. |
32 | */ |
33 | inline fbstring exceptionStr(const std::exception& e) { |
34 | #ifdef FOLLY_HAS_RTTI |
35 | fbstring rv(demangle(typeid(e))); |
36 | rv += ": " ; |
37 | #else |
38 | fbstring rv("Exception (no RTTI available): " ); |
39 | #endif |
40 | rv += e.what(); |
41 | return rv; |
42 | } |
43 | |
44 | // Empirically, this indicates if the runtime supports |
45 | // std::exception_ptr, as not all (arm, for instance) do. |
46 | #if defined(__GNUC__) && defined(__GCC_ATOMIC_INT_LOCK_FREE) && \ |
47 | __GCC_ATOMIC_INT_LOCK_FREE > 1 |
48 | inline fbstring exceptionStr(std::exception_ptr ep) { |
49 | if (!kHasExceptions) { |
50 | return "Exception (catch unavailable)" ; |
51 | } |
52 | return catch_exception( |
53 | [&]() -> fbstring { |
54 | return catch_exception<std::exception const&>( |
55 | [&]() -> fbstring { |
56 | std::rethrow_exception(ep); |
57 | assume_unreachable(); |
58 | }, |
59 | [](auto&& e) { return exceptionStr(e); }); |
60 | }, |
61 | []() -> fbstring { return "<unknown exception>" ; }); |
62 | } |
63 | #endif |
64 | |
65 | template <typename E> |
66 | auto exceptionStr(const E& e) -> typename std:: |
67 | enable_if<!std::is_base_of<std::exception, E>::value, fbstring>::type { |
68 | #ifdef FOLLY_HAS_RTTI |
69 | return demangle(typeid(e)); |
70 | #else |
71 | (void)e; |
72 | return "Exception (no RTTI available)" ; |
73 | #endif |
74 | } |
75 | |
76 | } // namespace folly |
77 | |