c1440a57a40a9f67d84d8301ba4babd081560be6
[folly.git] / folly / ExceptionWrapper.cpp
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 #include <folly/ExceptionWrapper.h>
17
18 #include <iostream>
19
20 #include <folly/Logging.h>
21
22 namespace folly {
23
24 constexpr exception_wrapper::VTable const exception_wrapper::uninit_;
25 constexpr exception_wrapper::VTable const exception_wrapper::ExceptionPtr::ops_;
26 constexpr exception_wrapper::VTable const exception_wrapper::SharedPtr::ops_;
27
28 namespace {
29 std::exception const* get_std_exception_(std::exception_ptr eptr) noexcept {
30   try {
31     std::rethrow_exception(eptr);
32   } catch (const std::exception& ex) {
33     return &ex;
34   } catch (...) {
35     return nullptr;
36   }
37 }
38 }
39
40 exception_wrapper::exception_wrapper(std::exception_ptr ptr) noexcept
41     : exception_wrapper{} {
42   if (ptr) {
43     if (auto e = get_std_exception_(ptr)) {
44       LOG(DFATAL)
45           << "Performance error: Please construct exception_wrapper with a "
46              "reference to the std::exception along with the "
47              "std::exception_ptr.";
48       *this = exception_wrapper{std::move(ptr), *e};
49     } else {
50       Unknown uk;
51       *this = exception_wrapper{ptr, uk};
52     }
53   }
54 }
55
56 [[noreturn]] void exception_wrapper::onNoExceptionError() {
57   std::ios_base::Init ioinit_; // ensure std::cerr is alive
58   std::cerr
59       << "Cannot use `throwException` with an empty folly::exception_wrapper"
60       << std::endl;
61   std::terminate();
62 }
63
64 fbstring exceptionStr(exception_wrapper const& ew) {
65   return ew.what();
66 }
67
68 } // folly