3f9f9688f754f8ce47a389a6308fca1d5a9b532e
[folly.git] / folly / ExceptionWrapper.h
1 /*
2  * Copyright 2015 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 #ifndef FOLLY_EXCEPTIONWRAPPER_H
18 #define FOLLY_EXCEPTIONWRAPPER_H
19
20 #include <cassert>
21 #include <exception>
22 #include <memory>
23 #include <folly/String.h>
24 #include <folly/detail/ExceptionWrapper.h>
25
26 namespace folly {
27
28 /*
29  * Throwing exceptions can be a convenient way to handle errors. Storing
30  * exceptions in an exception_ptr makes it easy to handle exceptions in a
31  * different thread or at a later time. exception_ptr can also be used in a very
32  * generic result/exception wrapper.
33  *
34  * However, there are some issues with throwing exceptions and
35  * std::exception_ptr. These issues revolve around throw being expensive,
36  * particularly in a multithreaded environment (see
37  * ExceptionWrapperBenchmark.cpp).
38  *
39  * Imagine we have a library that has an API which returns a result/exception
40  * wrapper. Let's consider some approaches for implementing this wrapper.
41  * First, we could store a std::exception. This approach loses the derived
42  * exception type, which can make exception handling more difficult for users
43  * that prefer rethrowing the exception. We could use a folly::dynamic for every
44  * possible type of exception. This is not very flexible - adding new types of
45  * exceptions requires a change to the result/exception wrapper. We could use an
46  * exception_ptr. However, constructing an exception_ptr as well as accessing
47  * the error requires a call to throw. That means that there will be two calls
48  * to throw in order to process the exception. For performance sensitive
49  * applications, this may be unacceptable.
50  *
51  * exception_wrapper is designed to handle exception management for both
52  * convenience and high performance use cases. make_exception_wrapper is
53  * templated on derived type, allowing us to rethrow the exception properly for
54  * users that prefer convenience. These explicitly named exception types can
55  * therefore be handled without any peformance penalty.  exception_wrapper is
56  * also flexible enough to accept any type. If a caught exception is not of an
57  * explicitly named type, then std::exception_ptr is used to preserve the
58  * exception state. For performance sensitive applications, the accessor methods
59  * can test or extract a pointer to a specific exception type with very little
60  * overhead.
61  *
62  * Example usage:
63  *
64  * exception_wrapper globalExceptionWrapper;
65  *
66  * // Thread1
67  * void doSomethingCrazy() {
68  *   int rc = doSomethingCrazyWithLameReturnCodes();
69  *   if (rc == NAILED_IT) {
70  *     globalExceptionWrapper = exception_wrapper();
71  *   } else if (rc == FACE_PLANT) {
72  *     globalExceptionWrapper = make_exception_wrapper<FacePlantException>();
73  *   } else if (rc == FAIL_WHALE) {
74  *     globalExceptionWrapper = make_exception_wrapper<FailWhaleException>();
75  *   }
76  * }
77  *
78  * // Thread2: Exceptions are ok!
79  * void processResult() {
80  *   try {
81  *     globalExceptionWrapper.throwException();
82  *   } catch (const FacePlantException& e) {
83  *     LOG(ERROR) << "FACEPLANT!";
84  *   } catch (const FailWhaleException& e) {
85  *     LOG(ERROR) << "FAILWHALE!";
86  *   }
87  * }
88  *
89  * // Thread2: Exceptions are bad!
90  * void processResult() {
91  *   auto ep = globalExceptionWrapper.get();
92  *   if (!ep.with_exception<FacePlantException>([&](
93  *     FacePlantException& faceplant) {
94  *       LOG(ERROR) << "FACEPLANT";
95  *     })) {
96  *     ep.with_exception<FailWhaleException>([&](
97  *       FailWhaleException& failwhale) {
98  *         LOG(ERROR) << "FAILWHALE!";
99  *       });
100  *   }
101  * }
102  *
103  */
104 class exception_wrapper {
105  protected:
106   template <typename Ex>
107   struct optimize;
108
109  public:
110   exception_wrapper() = default;
111
112   // Implicitly construct an exception_wrapper from a qualifying exception.
113   // See the optimize struct for details.
114   template <typename Ex, typename =
115     typename std::enable_if<optimize<Ex>::value>::type>
116   /* implicit */ exception_wrapper(Ex&& exn) {
117     item_ = std::make_shared<Ex>(std::forward<Ex>(exn));
118     throwfn_ = folly::detail::Thrower<Ex>::doThrow;
119   }
120
121   // The following two constructors are meant to emulate the behavior of
122   // try_and_catch in performance sensitive code as well as to be flexible
123   // enough to wrap exceptions of unknown type. There is an overload that
124   // takes an exception reference so that the wrapper can extract and store
125   // the exception's type and what() when possible.
126   //
127   // The canonical use case is to construct an all-catching exception wrapper
128   // with minimal overhead like so:
129   //
130   //   try {
131   //     // some throwing code
132   //   } catch (const std::exception& e) {
133   //     // won't lose e's type and what()
134   //     exception_wrapper ew{std::current_exception(), e};
135   //   } catch (...) {
136   //     // everything else
137   //     exception_wrapper ew{std::current_exception()};
138   //   }
139   //
140   // try_and_catch is cleaner and preferable. Use it unless you're sure you need
141   // something like this instead.
142   template <typename Ex>
143   explicit exception_wrapper(std::exception_ptr eptr, Ex& exn) {
144     assign_eptr(eptr, exn);
145   }
146
147   explicit exception_wrapper(std::exception_ptr eptr) {
148     assign_eptr(eptr);
149   }
150
151   void throwException() const {
152     if (throwfn_) {
153       throwfn_(item_.get());
154     } else if (eptr_) {
155       std::rethrow_exception(eptr_);
156     }
157   }
158
159   explicit operator bool() const {
160     return item_ || eptr_;
161   }
162
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 {
169     if (item_) {
170       return a.item_ && item_.get() == a.item_.get();
171     } else {
172       return eptr_ == a.eptr_;
173     }
174   }
175
176   bool operator!=(const exception_wrapper& a) const {
177     return !(*this == a);
178   }
179
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(); }
186
187   fbstring what() const {
188     if (item_) {
189       return exceptionStr(*item_);
190     } else if (eptr_) {
191       return estr_;
192     } else {
193       return fbstring();
194     }
195   }
196
197   fbstring class_name() const {
198     if (item_) {
199       auto& i = *item_;
200       return demangle(typeid(i));
201     } else if (eptr_) {
202       return ename_;
203     } else {
204       return fbstring();
205     }
206   }
207
208   template <class Ex>
209   bool is_compatible_with() const {
210     if (item_) {
211       return dynamic_cast<const Ex*>(item_.get());
212     } else if (eptr_) {
213       try {
214         std::rethrow_exception(eptr_);
215       } catch (std::exception& e) {
216         return dynamic_cast<const Ex*>(&e);
217       } catch (...) {
218         // fall through
219       }
220     }
221     return false;
222   }
223
224   // If this exception wrapper wraps an exception of type Ex, with_exception
225   // will call f with the wrapped exception as an argument and return true, and
226   // will otherwise return false.
227   template <class Ex, class F>
228   typename std::enable_if<
229     std::is_base_of<std::exception, typename std::decay<Ex>::type>::value,
230     bool>::type
231   with_exception(F f) {
232     return with_exception1<typename std::decay<Ex>::type>(f, this);
233   }
234
235   // Const overload
236   template <class Ex, class F>
237   typename std::enable_if<
238     std::is_base_of<std::exception, typename std::decay<Ex>::type>::value,
239     bool>::type
240   with_exception(F f) const {
241     return with_exception1<const typename std::decay<Ex>::type>(f, this);
242   }
243
244   // Overload for non-exceptions. Always rethrows.
245   template <class Ex, class F>
246   typename std::enable_if<
247     !std::is_base_of<std::exception, typename std::decay<Ex>::type>::value,
248     bool>::type
249   with_exception(F f) const {
250     try {
251       throwException();
252     } catch (typename std::decay<Ex>::type& e) {
253       f(e);
254       return true;
255     } catch (...) {
256       // fall through
257     }
258     return false;
259   }
260
261   std::exception_ptr getExceptionPtr() const {
262     if (eptr_) {
263       return eptr_;
264     }
265
266     try {
267       throwException();
268     } catch (...) {
269       return std::current_exception();
270     }
271     return std::exception_ptr();
272   }
273
274 protected:
275   template <typename Ex>
276   struct optimize {
277     static const bool value =
278       std::is_base_of<std::exception, Ex>::value &&
279       std::is_copy_assignable<Ex>::value &&
280       !std::is_abstract<Ex>::value;
281   };
282
283   template <typename Ex>
284   void assign_eptr(std::exception_ptr eptr, Ex& e) {
285     this->eptr_ = eptr;
286     this->estr_ = exceptionStr(e).toStdString();
287     this->ename_ = demangle(typeid(e)).toStdString();
288   }
289
290   void assign_eptr(std::exception_ptr eptr) {
291     this->eptr_ = eptr;
292   }
293
294   // Optimized case: if we know what type the exception is, we can
295   // store a copy of the concrete type, and a helper function so we
296   // can rethrow it.
297   std::shared_ptr<std::exception> item_;
298   void (*throwfn_)(std::exception*){nullptr};
299   // Fallback case: store the library wrapper, which is less efficient
300   // but gets the job done.  Also store exceptionPtr() the name of the
301   // exception type, so we can at least get those back out without
302   // having to rethrow.
303   std::exception_ptr eptr_;
304   std::string estr_;
305   std::string ename_;
306
307   template <class T, class... Args>
308   friend exception_wrapper make_exception_wrapper(Args&&... args);
309
310 private:
311   // What makes this useful is that T can be exception_wrapper* or
312   // const exception_wrapper*, and the compiler will use the
313   // instantiation which works with F.
314   template <class Ex, class F, class T>
315   static bool with_exception1(F f, T* that) {
316     if (that->item_) {
317       if (auto ex = dynamic_cast<Ex*>(that->item_.get())) {
318         f(*ex);
319         return true;
320       }
321     } else if (that->eptr_) {
322       try {
323         std::rethrow_exception(that->eptr_);
324       } catch (std::exception& e) {
325         if (auto ex = dynamic_cast<Ex*>(&e)) {
326           f(*ex);
327           return true;
328         }
329       } catch (...) {
330         // fall through
331       }
332     }
333     return false;
334   }
335 };
336
337 template <class T, class... Args>
338 exception_wrapper make_exception_wrapper(Args&&... args) {
339   exception_wrapper ew;
340   ew.item_ = std::make_shared<T>(std::forward<Args>(args)...);
341   ew.throwfn_ = folly::detail::Thrower<T>::doThrow;
342   return ew;
343 }
344
345 // For consistency with exceptionStr() functions in String.h
346 inline fbstring exceptionStr(const exception_wrapper& ew) {
347   return ew.what();
348 }
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 template <typename... Exceptions>
391 class try_and_catch;
392
393 template <typename LastException, typename... Exceptions>
394 class try_and_catch<LastException, Exceptions...> :
395     public try_and_catch<Exceptions...> {
396  public:
397   template <typename F>
398   explicit try_and_catch(F&& fn) : Base() {
399     call_fn(fn);
400   }
401
402  protected:
403   typedef try_and_catch<Exceptions...> Base;
404
405   try_and_catch() : Base() {}
406
407   template <typename Ex>
408   typename std::enable_if<!exception_wrapper::optimize<Ex>::value>::type
409   assign_exception(Ex& e, std::exception_ptr eptr) {
410     exception_wrapper::assign_eptr(eptr, e);
411   }
412
413   template <typename Ex>
414   typename std::enable_if<exception_wrapper::optimize<Ex>::value>::type
415   assign_exception(Ex& e, std::exception_ptr eptr) {
416     this->item_ = std::make_shared<Ex>(e);
417     this->throwfn_ = folly::detail::Thrower<Ex>::doThrow;
418   }
419
420   template <typename F>
421   void call_fn(F&& fn) {
422     try {
423       Base::call_fn(std::move(fn));
424     } catch (LastException& e) {
425       if (typeid(e) == typeid(LastException&)) {
426         assign_exception(e, std::current_exception());
427       } else {
428         exception_wrapper::assign_eptr(std::current_exception(), e);
429       }
430     }
431   }
432 };
433
434 template<>
435 class try_and_catch<> : public exception_wrapper {
436  public:
437   try_and_catch() {}
438
439  protected:
440   template <typename F>
441   void call_fn(F&& fn) {
442     fn();
443   }
444 };
445 }
446 #endif