2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <type_traits>
25 #include <folly/ExceptionString.h>
26 #include <folly/FBString.h>
27 #include <folly/detail/ExceptionWrapper.h>
32 * Throwing exceptions can be a convenient way to handle errors. Storing
33 * exceptions in an exception_ptr makes it easy to handle exceptions in a
34 * different thread or at a later time. exception_ptr can also be used in a very
35 * generic result/exception wrapper.
37 * However, there are some issues with throwing exceptions and
38 * std::exception_ptr. These issues revolve around throw being expensive,
39 * particularly in a multithreaded environment (see
40 * ExceptionWrapperBenchmark.cpp).
42 * Imagine we have a library that has an API which returns a result/exception
43 * wrapper. Let's consider some approaches for implementing this wrapper.
44 * First, we could store a std::exception. This approach loses the derived
45 * exception type, which can make exception handling more difficult for users
46 * that prefer rethrowing the exception. We could use a folly::dynamic for every
47 * possible type of exception. This is not very flexible - adding new types of
48 * exceptions requires a change to the result/exception wrapper. We could use an
49 * exception_ptr. However, constructing an exception_ptr as well as accessing
50 * the error requires a call to throw. That means that there will be two calls
51 * to throw in order to process the exception. For performance sensitive
52 * applications, this may be unacceptable.
54 * exception_wrapper is designed to handle exception management for both
55 * convenience and high performance use cases. make_exception_wrapper is
56 * templated on derived type, allowing us to rethrow the exception properly for
57 * users that prefer convenience. These explicitly named exception types can
58 * therefore be handled without any peformance penalty. exception_wrapper is
59 * also flexible enough to accept any type. If a caught exception is not of an
60 * explicitly named type, then std::exception_ptr is used to preserve the
61 * exception state. For performance sensitive applications, the accessor methods
62 * can test or extract a pointer to a specific exception type with very little
67 * exception_wrapper globalExceptionWrapper;
70 * void doSomethingCrazy() {
71 * int rc = doSomethingCrazyWithLameReturnCodes();
72 * if (rc == NAILED_IT) {
73 * globalExceptionWrapper = exception_wrapper();
74 * } else if (rc == FACE_PLANT) {
75 * globalExceptionWrapper = make_exception_wrapper<FacePlantException>();
76 * } else if (rc == FAIL_WHALE) {
77 * globalExceptionWrapper = make_exception_wrapper<FailWhaleException>();
81 * // Thread2: Exceptions are ok!
82 * void processResult() {
84 * globalExceptionWrapper.throwException();
85 * } catch (const FacePlantException& e) {
86 * LOG(ERROR) << "FACEPLANT!";
87 * } catch (const FailWhaleException& e) {
88 * LOG(ERROR) << "FAILWHALE!";
92 * // Thread2: Exceptions are bad!
93 * void processResult() {
94 * globalExceptionWrapper.with_exception(
95 * [&](FacePlantException& faceplant) {
96 * LOG(ERROR) << "FACEPLANT";
98 * globalExceptionWrapper.with_exception(
99 * [&](FailWhaleException& failwhale) {
100 * LOG(ERROR) << "FAILWHALE!";
102 * LOG(FATAL) << "Unrecognized exception";
106 class exception_wrapper {
108 template <typename Ex>
112 exception_wrapper() = default;
114 // Implicitly construct an exception_wrapper from a qualifying exception.
115 // See the optimize struct for details.
116 template <typename Ex, typename =
117 typename std::enable_if<optimize<typename std::decay<Ex>::type>::value>
119 /* implicit */ exception_wrapper(Ex&& exn) {
120 typedef typename std::decay<Ex>::type DEx;
121 item_ = std::make_shared<DEx>(std::forward<Ex>(exn));
122 throwfn_ = folly::detail::Thrower<DEx>::doThrow;
125 // The following two constructors are meant to emulate the behavior of
126 // try_and_catch in performance sensitive code as well as to be flexible
127 // enough to wrap exceptions of unknown type. There is an overload that
128 // takes an exception reference so that the wrapper can extract and store
129 // the exception's type and what() when possible.
131 // The canonical use case is to construct an all-catching exception wrapper
132 // with minimal overhead like so:
135 // // some throwing code
136 // } catch (const std::exception& e) {
137 // // won't lose e's type and what()
138 // exception_wrapper ew{std::current_exception(), e};
140 // // everything else
141 // exception_wrapper ew{std::current_exception()};
144 // try_and_catch is cleaner and preferable. Use it unless you're sure you need
145 // something like this instead.
146 template <typename Ex>
147 explicit exception_wrapper(std::exception_ptr eptr, Ex& exn) {
148 assign_eptr(eptr, exn);
151 explicit exception_wrapper(std::exception_ptr eptr) {
155 // If the exception_wrapper does not contain an exception, std::terminate()
156 // is invoked to assure the [[noreturn]] behaviour.
157 [[noreturn]] void throwException() const;
159 explicit operator bool() const {
160 return item_ || eptr_;
163 // This implementation is similar to std::exception_ptr's implementation
164 // where two exception_wrappers are equal when the address in the underlying
165 // reference field both point to the same exception object. The reference
166 // field remains the same when the exception_wrapper is copied or when
167 // the exception_wrapper is "rethrown".
168 bool operator==(const exception_wrapper& a) const {
170 return a.item_ && item_.get() == a.item_.get();
172 return eptr_ == a.eptr_;
176 bool operator!=(const exception_wrapper& a) const {
177 return !(*this == a);
180 // This will return a non-nullptr only if the exception is held as a
181 // copy. It is the only interface which will distinguish between an
182 // exception held this way, and by exception_ptr. You probably
183 // shouldn't use it at all.
184 std::exception* getCopied() { return item_.get(); }
185 const std::exception* getCopied() const { return item_.get(); }
187 fbstring what() const;
188 fbstring class_name() const;
191 bool is_compatible_with() const {
193 return dynamic_cast<const Ex*>(item_.get());
196 std::rethrow_exception(eptr_);
197 } catch (typename std::decay<Ex>::type&) {
207 bool with_exception(F&& f) {
208 using arg_type = typename functor_traits<F>::arg_type_decayed;
209 return with_exception<arg_type>(std::forward<F>(f));
213 bool with_exception(F&& f) const {
214 using arg_type = typename functor_traits<F>::arg_type_decayed;
215 return with_exception<const arg_type>(std::forward<F>(f));
218 // If this exception wrapper wraps an exception of type Ex, with_exception
219 // will call f with the wrapped exception as an argument and return true, and
220 // will otherwise return false.
221 template <class Ex, class F>
222 typename std::enable_if<
223 std::is_base_of<std::exception, typename std::decay<Ex>::type>::value,
225 with_exception(F f) {
226 return with_exception1<typename std::decay<Ex>::type>(f, this);
230 template <class Ex, class F>
231 typename std::enable_if<
232 std::is_base_of<std::exception, typename std::decay<Ex>::type>::value,
234 with_exception(F f) const {
235 return with_exception1<const typename std::decay<Ex>::type>(f, this);
238 // Overload for non-exceptions. Always rethrows.
239 template <class Ex, class F>
240 typename std::enable_if<
241 !std::is_base_of<std::exception, typename std::decay<Ex>::type>::value,
243 with_exception(F f) const {
248 } catch (typename std::decay<Ex>::type& e) {
257 std::exception_ptr getExceptionPtr() const {
267 return std::current_exception();
269 return std::exception_ptr();
273 template <typename Ex>
275 static const bool value =
276 std::is_base_of<std::exception, Ex>::value &&
277 std::is_copy_assignable<Ex>::value &&
278 !std::is_abstract<Ex>::value;
281 template <typename Ex>
282 void assign_eptr(std::exception_ptr eptr, Ex& e) {
284 this->estr_ = exceptionStr(e).toStdString();
285 this->ename_ = demangle(typeid(e)).toStdString();
288 void assign_eptr(std::exception_ptr eptr) {
292 // Optimized case: if we know what type the exception is, we can
293 // store a copy of the concrete type, and a helper function so we
295 std::shared_ptr<std::exception> item_;
296 void (*throwfn_)(std::exception*){nullptr};
297 // Fallback case: store the library wrapper, which is less efficient
298 // but gets the job done. Also store exceptionPtr() the name of the
299 // exception type, so we can at least get those back out without
300 // having to rethrow.
301 std::exception_ptr eptr_;
305 template <class T, class... Args>
306 friend exception_wrapper make_exception_wrapper(Args&&... args);
309 template <typename F>
310 struct functor_traits {
311 template <typename T>
313 template <typename C, typename R, typename A>
314 struct impl<R(C::*)(A)> { using arg_type = A; };
315 template <typename C, typename R, typename A>
316 struct impl<R(C::*)(A) const> { using arg_type = A; };
317 using functor_decayed = typename std::decay<F>::type;
318 using functor_op = decltype(&functor_decayed::operator());
319 using arg_type = typename impl<functor_op>::arg_type;
320 using arg_type_decayed = typename std::decay<arg_type>::type;
323 // What makes this useful is that T can be exception_wrapper* or
324 // const exception_wrapper*, and the compiler will use the
325 // instantiation which works with F.
326 template <class Ex, class F, class T>
327 static bool with_exception1(F f, T* that) {
329 if (auto ex = dynamic_cast<Ex*>(that->item_.get())) {
333 } else if (that->eptr_) {
335 std::rethrow_exception(that->eptr_);
347 template <class T, class... Args>
348 exception_wrapper make_exception_wrapper(Args&&... args) {
349 exception_wrapper ew;
350 ew.item_ = std::make_shared<T>(std::forward<Args>(args)...);
351 ew.throwfn_ = folly::detail::Thrower<T>::doThrow;
355 // For consistency with exceptionStr() functions in String.h
356 fbstring exceptionStr(const exception_wrapper& ew);
359 * try_and_catch is a simple replacement for try {} catch(){} that allows you to
360 * specify which derived exceptions you would like to catch and store in an
363 * Because we cannot build an equivalent of std::current_exception(), we need
364 * to catch every derived exception that we are interested in catching.
366 * Exceptions should be listed in the reverse order that you would write your
367 * catch statements (that is, std::exception& should be first).
369 * NOTE: Although implemented as a derived class (for syntactic delight), don't
370 * be confused - you should not pass around try_and_catch objects!
374 * // This catches my runtime_error and if I call throwException() on ew, it
375 * // will throw a runtime_error
376 * auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
377 * if (badThingHappens()) {
378 * throw std::runtime_error("ZOMG!");
382 * // This will catch the exception and if I call throwException() on ew, it
383 * // will throw a std::exception
384 * auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
385 * if (badThingHappens()) {
386 * throw std::exception();
390 * // This will not catch the exception and it will be thrown.
391 * auto ew = folly::try_and_catch<std::runtime_error>([=]() {
392 * if (badThingHappens()) {
393 * throw std::exception();
398 template <typename... Exceptions>
401 template <typename LastException, typename... Exceptions>
402 class try_and_catch<LastException, Exceptions...> :
403 public try_and_catch<Exceptions...> {
405 template <typename F>
406 explicit try_and_catch(F&& fn) : Base() {
411 typedef try_and_catch<Exceptions...> Base;
413 try_and_catch() : Base() {}
415 template <typename Ex>
416 typename std::enable_if<!exception_wrapper::optimize<Ex>::value>::type
417 assign_exception(Ex& e, std::exception_ptr eptr) {
418 exception_wrapper::assign_eptr(eptr, e);
421 template <typename Ex>
422 typename std::enable_if<exception_wrapper::optimize<Ex>::value>::type
423 assign_exception(Ex& e, std::exception_ptr /*eptr*/) {
424 this->item_ = std::make_shared<Ex>(e);
425 this->throwfn_ = folly::detail::Thrower<Ex>::doThrow;
428 template <typename F>
429 void call_fn(F&& fn) {
431 Base::call_fn(std::move(fn));
432 } catch (LastException& e) {
433 if (typeid(e) == typeid(LastException&)) {
434 assign_exception(e, std::current_exception());
436 exception_wrapper::assign_eptr(std::current_exception(), e);
443 class try_and_catch<> : public exception_wrapper {
445 try_and_catch() = default;
448 template <typename F>
449 void call_fn(F&& fn) {