ExceptionString.h 1.8 KB

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