All template params for PriorityMPMCQueue
[folly.git] / folly / ExceptionWrapper.h
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
17 #pragma once
18
19 #include <exception>
20 #include <memory>
21 #include <string>
22 #include <tuple>
23 #include <type_traits>
24 #include <utility>
25
26 #include <folly/ExceptionString.h>
27 #include <folly/FBString.h>
28 #include <folly/Traits.h>
29
30 namespace folly {
31
32 /*
33  * Throwing exceptions can be a convenient way to handle errors. Storing
34  * exceptions in an exception_ptr makes it easy to handle exceptions in a
35  * different thread or at a later time. exception_ptr can also be used in a very
36  * generic result/exception wrapper.
37  *
38  * However, there are some issues with throwing exceptions and
39  * std::exception_ptr. These issues revolve around throw being expensive,
40  * particularly in a multithreaded environment (see
41  * ExceptionWrapperBenchmark.cpp).
42  *
43  * Imagine we have a library that has an API which returns a result/exception
44  * wrapper. Let's consider some approaches for implementing this wrapper.
45  * First, we could store a std::exception. This approach loses the derived
46  * exception type, which can make exception handling more difficult for users
47  * that prefer rethrowing the exception. We could use a folly::dynamic for every
48  * possible type of exception. This is not very flexible - adding new types of
49  * exceptions requires a change to the result/exception wrapper. We could use an
50  * exception_ptr. However, constructing an exception_ptr as well as accessing
51  * the error requires a call to throw. That means that there will be two calls
52  * to throw in order to process the exception. For performance sensitive
53  * applications, this may be unacceptable.
54  *
55  * exception_wrapper is designed to handle exception management for both
56  * convenience and high performance use cases. make_exception_wrapper is
57  * templated on derived type, allowing us to rethrow the exception properly for
58  * users that prefer convenience. These explicitly named exception types can
59  * therefore be handled without any peformance penalty.  exception_wrapper is
60  * also flexible enough to accept any type. If a caught exception is not of an
61  * explicitly named type, then std::exception_ptr is used to preserve the
62  * exception state. For performance sensitive applications, the accessor methods
63  * can test or extract a pointer to a specific exception type with very little
64  * overhead.
65  *
66  * \par Example usage:
67  * \par
68  * \code
69  * exception_wrapper globalExceptionWrapper;
70  *
71  * // Thread1
72  * void doSomethingCrazy() {
73  *   int rc = doSomethingCrazyWithLameReturnCodes();
74  *   if (rc == NAILED_IT) {
75  *     globalExceptionWrapper = exception_wrapper();
76  *   } else if (rc == FACE_PLANT) {
77  *     globalExceptionWrapper = make_exception_wrapper<FacePlantException>();
78  *   } else if (rc == FAIL_WHALE) {
79  *     globalExceptionWrapper = make_exception_wrapper<FailWhaleException>();
80  *   }
81  * }
82  *
83  * // Thread2: Exceptions are ok!
84  * void processResult() {
85  *   try {
86  *     globalExceptionWrapper.throwException();
87  *   } catch (const FacePlantException& e) {
88  *     LOG(ERROR) << "FACEPLANT!";
89  *   } catch (const FailWhaleException& e) {
90  *     LOG(ERROR) << "FAILWHALE!";
91  *   }
92  * }
93  *
94  * // Thread2: Exceptions are bad!
95  * void processResult() {
96  *   globalExceptionWrapper.with_exception(
97  *       [&](FacePlantException& faceplant) {
98  *         LOG(ERROR) << "FACEPLANT";
99  *       }) ||
100  *   globalExceptionWrapper.with_exception(
101  *       [&](FailWhaleException& failwhale) {
102  *         LOG(ERROR) << "FAILWHALE!";
103  *       }) ||
104  *   LOG(FATAL) << "Unrecognized exception";
105  * }
106  * \endcode
107  *
108  */
109 class exception_wrapper {
110  private:
111   template <typename T>
112   using is_exception_ = std::is_base_of<std::exception, T>;
113
114  public:
115   exception_wrapper() = default;
116
117   template <
118       typename Ex,
119       typename DEx = _t<std::decay<Ex>>,
120       typename = _t<std::enable_if<is_exception_<DEx>::value>>,
121       typename = decltype(DEx(std::forward<Ex>(std::declval<Ex&&>())))>
122   /* implicit */ exception_wrapper(Ex&& exn) {
123     assign_sptr<DEx>(std::forward<Ex>(exn));
124   }
125
126   // The following two constructors are meant to emulate the behavior of
127   // try_and_catch in performance sensitive code as well as to be flexible
128   // enough to wrap exceptions of unknown type. There is an overload that
129   // takes an exception reference so that the wrapper can extract and store
130   // the exception's type and what() when possible.
131   //
132   // The canonical use case is to construct an all-catching exception wrapper
133   // with minimal overhead like so:
134   //
135   //   try {
136   //     // some throwing code
137   //   } catch (const std::exception& e) {
138   //     // won't lose e's type and what()
139   //     exception_wrapper ew{std::current_exception(), e};
140   //   } catch (...) {
141   //     // everything else
142   //     exception_wrapper ew{std::current_exception()};
143   //   }
144   //
145   // try_and_catch is cleaner and preferable. Use it unless you're sure you need
146   // something like this instead.
147   template <typename Ex>
148   explicit exception_wrapper(std::exception_ptr eptr, Ex& exn) {
149     assign_eptr(eptr, exn);
150   }
151
152   explicit exception_wrapper(std::exception_ptr eptr) {
153     assign_eptr(eptr);
154   }
155
156   // If the exception_wrapper does not contain an exception, std::terminate()
157   // is invoked to assure the [[noreturn]] behaviour.
158   [[noreturn]] void throwException() const;
159
160   explicit operator bool() const {
161     return item_ || eptr_;
162   }
163
164   // This implementation is similar to std::exception_ptr's implementation
165   // where two exception_wrappers are equal when the address in the underlying
166   // reference field both point to the same exception object.  The reference
167   // field remains the same when the exception_wrapper is copied or when
168   // the exception_wrapper is "rethrown".
169   bool operator==(const exception_wrapper& a) const {
170     if (item_) {
171       return a.item_ && item_.get() == a.item_.get();
172     } else {
173       return eptr_ == a.eptr_;
174     }
175   }
176
177   bool operator!=(const exception_wrapper& a) const {
178     return !(*this == a);
179   }
180
181   // This will return a non-nullptr only if the exception is held as a
182   // copy.  It is the only interface which will distinguish between an
183   // exception held this way, and by exception_ptr.  You probably
184   // shouldn't use it at all.
185   std::exception* getCopied() { return item_.get(); }
186   const std::exception* getCopied() const { return item_.get(); }
187
188   fbstring what() const;
189   fbstring class_name() const;
190
191   template <class Ex>
192   bool is_compatible_with() const {
193     return with_exception<Ex>([](const Ex&) {});
194   }
195
196   template <class F>
197   bool with_exception(F&& f) {
198     using arg_type = _t<std::decay<typename functor_traits<F>::arg_type>>;
199     return with_exception<arg_type>(std::forward<F>(f));
200   }
201
202   template <class F>
203   bool with_exception(F&& f) const {
204     using arg_type = _t<std::decay<typename functor_traits<F>::arg_type>>;
205     return with_exception<arg_type>(std::forward<F>(f));
206   }
207
208   // If this exception wrapper wraps an exception of type Ex, with_exception
209   // will call f with the wrapped exception as an argument and return true, and
210   // will otherwise return false.
211   template <class Ex, class F>
212   bool with_exception(F f) {
213     return with_exception1<_t<std::decay<Ex>>>(std::forward<F>(f), this);
214   }
215
216   // Const overload
217   template <class Ex, class F>
218   bool with_exception(F f) const {
219     return with_exception1<_t<std::decay<Ex>>>(std::forward<F>(f), this);
220   }
221
222   std::exception_ptr to_exception_ptr() const {
223     if (eptr_) {
224       return eptr_;
225     }
226
227     try {
228       if (*this) {
229         throwException();
230       }
231     } catch (...) {
232       return std::current_exception();
233     }
234     return std::exception_ptr();
235   }
236
237  private:
238   template <typename Ex, typename... Args>
239   void assign_sptr(Args&&... args) {
240     this->item_ = std::make_shared<Ex>(std::forward<Args>(args)...);
241     this->throwfn_ = Thrower<Ex>::doThrow;
242   }
243
244   template <typename Ex>
245   _t<std::enable_if<is_exception_<Ex>::value>> assign_eptr(
246       std::exception_ptr eptr,
247       Ex& e) {
248     this->eptr_ = eptr;
249     this->eobj_ = &const_cast<_t<std::remove_const<Ex>>&>(e);
250   }
251
252   template <typename Ex>
253   _t<std::enable_if<!is_exception_<Ex>::value>> assign_eptr(
254       std::exception_ptr eptr,
255       Ex& e) {
256     this->eptr_ = eptr;
257     this->etype_ = &typeid(e);
258   }
259
260   void assign_eptr(std::exception_ptr eptr) {
261     this->eptr_ = eptr;
262   }
263
264   // Optimized case: if we know what type the exception is, we can
265   // store a copy of the concrete type, and a helper function so we
266   // can rethrow it.
267   std::shared_ptr<std::exception> item_;
268   void (*throwfn_)(std::exception&){nullptr};
269   // Fallback case: store the library wrapper, which is less efficient
270   // but gets the job done.  Also store exceptionPtr() the name of the
271   // exception type, so we can at least get those back out without
272   // having to rethrow.
273   std::exception_ptr eptr_;
274   std::exception* eobj_{nullptr};
275   const std::type_info* etype_{nullptr};
276
277   template <class T, class... Args>
278   friend exception_wrapper make_exception_wrapper(Args&&... args);
279
280  private:
281   template <typename F>
282   struct functor_traits {
283     template <typename T>
284     struct impl;
285     template <typename C, typename R, typename A>
286     struct impl<R(C::*)(A)> { using arg_type = A; };
287     template <typename C, typename R, typename A>
288     struct impl<R(C::*)(A) const> { using arg_type = A; };
289     using functor_op = decltype(&_t<std::decay<F>>::operator());
290     using arg_type = typename impl<functor_op>::arg_type;
291   };
292
293   template <class T>
294   class Thrower {
295    public:
296     static void doThrow(std::exception& obj) {
297       throw static_cast<T&>(obj);
298     }
299   };
300
301   template <typename T, typename F>
302   static _t<std::enable_if<is_exception_<T>::value, T*>>
303   try_dynamic_cast_exception(F* from) {
304     return dynamic_cast<T*>(from);
305   }
306   template <typename T, typename F>
307   static _t<std::enable_if<!is_exception_<T>::value, T*>>
308   try_dynamic_cast_exception(F*) {
309     return nullptr;
310   }
311
312   // What makes this useful is that T can be exception_wrapper* or
313   // const exception_wrapper*, and the compiler will use the
314   // instantiation which works with F.
315   template <class Ex, class F, class T>
316   static bool with_exception1(F f, T* that) {
317     using CEx = _t<std::conditional<std::is_const<T>::value, const Ex, Ex>>;
318     if (is_exception_<Ex>::value &&
319         (that->item_ || (that->eptr_ && that->eobj_))) {
320       auto raw =
321           that->item_ ? that->item_.get() : that->eptr_ ? that->eobj_ : nullptr;
322       if (auto ex = try_dynamic_cast_exception<CEx>(raw)) {
323         f(*ex);
324         return true;
325       }
326     } else if (that->eptr_) {
327       try {
328         std::rethrow_exception(that->eptr_);
329       } catch (CEx& e) {
330         f(e);
331         return true;
332       } catch (...) {
333         // fall through
334       }
335     }
336     return false;
337   }
338 };
339
340 template <class Ex, class... Args>
341 exception_wrapper make_exception_wrapper(Args&&... args) {
342   exception_wrapper ew;
343   ew.assign_sptr<Ex>(std::forward<Args>(args)...);
344   return ew;
345 }
346
347 // For consistency with exceptionStr() functions in ExceptionString.h
348 fbstring exceptionStr(const exception_wrapper& ew);
349
350 /*
351  * try_and_catch is a simple replacement for try {} catch(){} that allows you to
352  * specify which derived exceptions you would like to catch and store in an
353  * exception_wrapper.
354  *
355  * Because we cannot build an equivalent of std::current_exception(), we need
356  * to catch every derived exception that we are interested in catching.
357  *
358  * Exceptions should be listed in the reverse order that you would write your
359  * catch statements (that is, std::exception& should be first).
360  *
361  * NOTE: Although implemented as a derived class (for syntactic delight), don't
362  * be confused - you should not pass around try_and_catch objects!
363  *
364  * Example Usage:
365  *
366  * // This catches my runtime_error and if I call throwException() on ew, it
367  * // will throw a runtime_error
368  * auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
369  *   if (badThingHappens()) {
370  *     throw std::runtime_error("ZOMG!");
371  *   }
372  * });
373  *
374  * // This will catch the exception and if I call throwException() on ew, it
375  * // will throw a std::exception
376  * auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
377  *   if (badThingHappens()) {
378  *     throw std::exception();
379  *   }
380  * });
381  *
382  * // This will not catch the exception and it will be thrown.
383  * auto ew = folly::try_and_catch<std::runtime_error>([=]() {
384  *   if (badThingHappens()) {
385  *     throw std::exception();
386  *   }
387  * });
388  */
389
390 namespace try_and_catch_detail {
391
392 template <typename... Args>
393 using is_wrap_ctor = std::is_constructible<exception_wrapper, Args...>;
394
395 template <typename Ex>
396 inline _t<std::enable_if<!is_wrap_ctor<Ex&>::value, exception_wrapper>> make(
397     Ex& ex) {
398   return exception_wrapper(std::current_exception(), ex);
399 }
400
401 template <typename Ex>
402 inline _t<std::enable_if<is_wrap_ctor<Ex&>::value, exception_wrapper>> make(
403     Ex& ex) {
404   return typeid(Ex&) == typeid(ex)
405       ? exception_wrapper(ex)
406       : exception_wrapper(std::current_exception(), ex);
407 }
408
409 template <typename F>
410 inline exception_wrapper impl(F&& f) {
411   return (f(), exception_wrapper());
412 }
413
414 template <typename F, typename Ex, typename... Exs>
415 inline exception_wrapper impl(F&& f) {
416   try {
417     return impl<F, Exs...>(std::forward<F>(f));
418   } catch (Ex& ex) {
419     return make(ex);
420   }
421 }
422 } // try_and_catch_detail
423
424 template <typename... Exceptions, typename F>
425 exception_wrapper try_and_catch(F&& fn) {
426   return try_and_catch_detail::impl<F, Exceptions...>(std::forward<F>(fn));
427 }
428 } // folly