1 | /* |
2 | * Copyright (c) Facebook, Inc. and its affiliates. |
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 | #if 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 | inline fbstring exceptionStr(std::exception_ptr ep) { |
45 | if (!kHasExceptions) { |
46 | return "Exception (catch unavailable)" ; |
47 | } |
48 | return catch_exception( |
49 | [&]() -> fbstring { |
50 | return catch_exception<std::exception const&>( |
51 | [&]() -> fbstring { std::rethrow_exception(ep); }, |
52 | [](auto&& e) { return exceptionStr(e); }); |
53 | }, |
54 | []() -> fbstring { return "<unknown exception>" ; }); |
55 | } |
56 | |
57 | template <typename E> |
58 | auto exceptionStr(const E& e) -> typename std:: |
59 | enable_if<!std::is_base_of<std::exception, E>::value, fbstring>::type { |
60 | #if FOLLY_HAS_RTTI |
61 | return demangle(typeid(e)); |
62 | #else |
63 | (void)e; |
64 | return "Exception (no RTTI available)" ; |
65 | #endif |
66 | } |
67 | |
68 | } // namespace folly |
69 | |