exception_wrapper::from_exception_ptr
authorYedidya Feldblum <yfeldblum@fb.com>
Mon, 21 Aug 2017 18:38:39 +0000 (11:38 -0700)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Mon, 21 Aug 2017 18:49:59 +0000 (11:49 -0700)
Summary:
[Folly] `exception_wrapper::from_exception_ptr`.

A handry helper for converting from `std::exception_ptr` to `folly::exception_wrapper`.

Reviewed By: ericniebler

Differential Revision: D5668179

fbshipit-source-id: a81a60cb22a2a697714268e027af62dd8825d2c3

folly/ExceptionWrapper.cpp
folly/ExceptionWrapper.h
folly/test/ExceptionWrapperTest.cpp

index 6d14f0ad31bb5b3b9d4f30bfcd2fcb61b802cd01..7cda0b7645decc3fdd2bff3eaffbc73fa8edf2b3 100644 (file)
@@ -60,6 +60,20 @@ std::exception const* get_std_exception_(std::exception_ptr eptr) noexcept {
 }
 }
 
+exception_wrapper exception_wrapper::from_exception_ptr(
+    std::exception_ptr const& ptr) noexcept {
+  if (!ptr) {
+    return exception_wrapper();
+  }
+  try {
+    std::rethrow_exception(ptr);
+  } catch (std::exception& e) {
+    return exception_wrapper(std::current_exception(), e);
+  } catch (...) {
+    return exception_wrapper(std::current_exception());
+  }
+}
+
 exception_wrapper::exception_wrapper(std::exception_ptr ptr) noexcept
     : exception_wrapper{} {
   if (ptr) {
index 489d158a9c3b214de9020066e04b98f3a06b6a9f..eb493fc68c10429428515a8f6459429e24d01162 100644 (file)
@@ -368,6 +368,9 @@ class exception_wrapper final {
   static bool with_exception_(This& this_, Fn fn_);
 
  public:
+  static exception_wrapper from_exception_ptr(
+      std::exception_ptr const& eptr) noexcept;
+
   //! Default-constructs an empty `exception_wrapper`
   //! \post `type() == none()`
   exception_wrapper() noexcept {}
index e182196d36829297beab1bc6f2a09b547d6d2068..fdb68407296d159d76f2ab0ac4717f38e676e3d9 100644 (file)
@@ -209,6 +209,28 @@ TEST(ExceptionWrapper, get_or_make_exception_ptr_test) {
   EXPECT_FALSE(eptr);
 }
 
+TEST(ExceptionWrapper, from_exception_ptr_empty) {
+  auto ep = std::exception_ptr();
+  auto ew = exception_wrapper::from_exception_ptr(ep);
+  EXPECT_FALSE(bool(ew));
+}
+
+TEST(ExceptionWrapper, from_exception_ptr_exn) {
+  auto ep = std::make_exception_ptr(std::runtime_error("foo"));
+  auto ew = exception_wrapper::from_exception_ptr(ep);
+  EXPECT_TRUE(bool(ew));
+  EXPECT_EQ(ep, ew.to_exception_ptr());
+  EXPECT_TRUE(ew.is_compatible_with<std::runtime_error>());
+}
+
+TEST(ExceptionWrapper, from_exception_ptr_any) {
+  auto ep = std::make_exception_ptr<int>(12);
+  auto ew = exception_wrapper::from_exception_ptr(ep);
+  EXPECT_TRUE(bool(ew));
+  EXPECT_EQ(ep, ew.to_exception_ptr());
+  EXPECT_TRUE(ew.is_compatible_with<int>());
+}
+
 TEST(ExceptionWrapper, with_exception_ptr_empty) {
   auto ew = exception_wrapper(std::exception_ptr());
   EXPECT_EQ(exception_wrapper::none(), ew.type());