Verbosify exception tracer dumps
[folly.git] / folly / experimental / exception_tracer / ExceptionTracerTest.cpp
1 /*
2  * Copyright 2012 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
18 #include <stdexcept>
19
20 #include "folly/experimental/exception_tracer/ExceptionTracer.h"
21
22 void bar() {
23   throw std::runtime_error("hello");
24 }
25
26 void dumpExceptions(const char* prefix) {
27   std::cerr << "--- " << prefix << "\n";
28   auto exceptions = exception_tracer::getCurrentExceptions();
29   for (auto& exc : exceptions) {
30     std::cerr << exc << "\n";
31   }
32 }
33
34 void foo() {
35   try {
36     try {
37       bar();
38     } catch (const std::exception& e) {
39       dumpExceptions("foo: simple catch");
40       bar();
41     }
42   } catch (const std::exception& e) {
43     dumpExceptions("foo: catch, exception thrown from previous catch block");
44   }
45 }
46
47 void baz() {
48   try {
49     try {
50       bar();
51     } catch (...) {
52       dumpExceptions("baz: simple catch");
53       throw;
54     }
55   } catch (const std::exception& e) {
56     dumpExceptions("baz: catch rethrown exception");
57     throw "hello";
58   }
59 }
60
61 void testExceptionPtr1() {
62   std::exception_ptr exc;
63   try {
64     bar();
65   } catch (...) {
66     exc = std::current_exception();
67   }
68
69   try {
70     std::rethrow_exception(exc);
71   } catch (...) {
72     dumpExceptions("std::rethrow_exception 1");
73   }
74 }
75
76 void testExceptionPtr2() {
77   std::exception_ptr exc;
78   try {
79     throw std::out_of_range("x");
80   } catch (...) {
81     exc = std::current_exception();
82   }
83
84   try {
85     std::rethrow_exception(exc);
86   } catch (...) {
87     dumpExceptions("std::rethrow_exception 2");
88   }
89 }
90
91 int main(int argc, char *argv[]) {
92   foo();
93   testExceptionPtr1();
94   testExceptionPtr2();
95   baz();
96   return 0;
97 }
98