aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/terminate_handler/terminate_handler.cpp
blob: d7e8fbed95fcfcbf59b7d03bad0b982982188d06 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <cstdlib>
#include <exception>

#include <util/stream/output.h>
#include <util/system/backtrace.h>
#include <util/generic/yexception.h>

namespace {
    // Avoid infinite recursion if std::terminate is triggered anew by the
    // FancyTerminateHandler.
    thread_local int TerminateCount = 0;

    void FancyTerminateHandler() {
        switch (++TerminateCount) {
            case 1:
                break;
            case 2:
                Cerr << "FancyTerminateHandler called recursively" << Endl;
                [[fallthrough]];
            default:
                abort();
                break;
        }

        if (std::current_exception()) {
            Cerr << "Uncaught exception: " << CurrentExceptionMessage() << '\n';
        } else {
            Cerr << "Terminate for unknown reason (no current exception)\n";
        }
        PrintBackTrace();
        Cerr.Flush();
        abort();
    }

    [[maybe_unused]] auto _ = std::set_terminate(&FancyTerminateHandler);
}