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 #include <folly/ExceptionWrapper.h>
18 
19 #include <iostream>
20 
21 #include <folly/GLog.h>
22 
23 namespace folly {
24 
25 exception_wrapper::VTable const exception_wrapper::uninit_{
26     &noop_<void, exception_wrapper const*, exception_wrapper*>,
27     &noop_<void, exception_wrapper*, exception_wrapper*>,
28     &noop_<void, exception_wrapper*>,
29     &noop_<void, exception_wrapper const*>,
30     &uninit_type_,
31     &noop_<std::exception const*, exception_wrapper const*>,
32     &noop_<exception_wrapper, exception_wrapper const*>};
33 
34 exception_wrapper::VTable const exception_wrapper::ExceptionPtr::ops_{
35     copy_, move_, delete_, throw_, type_, get_exception_, get_exception_ptr_};
36 
37 exception_wrapper::VTable const exception_wrapper::SharedPtr::ops_{
38     copy_, move_, delete_, throw_, type_, get_exception_, get_exception_ptr_};
39 
from_exception_ptr(std::exception_ptr const & ptr)40 exception_wrapper exception_wrapper::from_exception_ptr(
41     std::exception_ptr const& ptr) noexcept {
42   return from_exception_ptr(folly::copy(ptr));
43 }
44 
from_exception_ptr(std::exception_ptr && ptr)45 exception_wrapper exception_wrapper::from_exception_ptr(
46     std::exception_ptr&& ptr) noexcept {
47   return !ptr ? exception_wrapper() : exception_wrapper(std::move(ptr));
48 }
49 
exception_wrapper(std::exception_ptr const & ptr)50 exception_wrapper::exception_wrapper(std::exception_ptr const& ptr) noexcept
51     : exception_wrapper{folly::copy(ptr)} {}
52 
exception_wrapper(std::exception_ptr && ptr)53 exception_wrapper::exception_wrapper(std::exception_ptr&& ptr) noexcept {
54   if (ptr) {
55     ::new (&eptr_) ExceptionPtr{std::move(ptr)};
56     vptr_ = &ExceptionPtr::ops_;
57   }
58 }
59 
onNoExceptionError(char const * const name)60 [[noreturn]] void exception_wrapper::onNoExceptionError(
61     char const* const name) {
62   std::ios_base::Init ioinit_; // ensure std::cerr is alive
63   std::cerr << "Cannot use `" << name
64             << "` with an empty folly::exception_wrapper" << std::endl;
65   std::terminate();
66 }
67 
exceptionStr(exception_wrapper const & ew)68 fbstring exceptionStr(exception_wrapper const& ew) {
69   return ew.what();
70 }
71 
72 } // namespace folly
73