Move folly/detail/Sleeper.h to folly/synchronization/detail/
[folly.git] / folly / ExceptionString.h
1 /*
2  * Copyright 2017 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   try {
50     std::rethrow_exception(ep);
51   } catch (const std::exception& e) {
52     return exceptionStr(e);
53   } catch (...) {
54     return "<unknown exception>";
55   }
56 }
57 #endif
58
59 template <typename E>
60 auto exceptionStr(const E& e) -> typename std::
61     enable_if<!std::is_base_of<std::exception, E>::value, fbstring>::type {
62 #ifdef FOLLY_HAS_RTTI
63   return demangle(typeid(e));
64 #else
65   return "Exception (no RTTI available)";
66 #endif
67 }
68
69 } // namespace folly