Echo Writes Code

handlers.cpp

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "crucible/core/handlers.hpp"

#include <cstdlib>
#include <exception>
#include <iostream>

#include "crucible/core/backtrace.hpp"
#include "crucible/core/console.hpp"
#include "crucible/core/format.hpp"
#include "crucible/core/iterators.hpp"
#include "crucible/core/memory.hpp"
#include "crucible/core/string.hpp"

namespace crucible
{
  namespace
  {
    auto handle_backtrace_failure(Backtrace_Error const &/* error */) -> void
    {
      console().format_err_line("BACKTRACE FAILED");
      console().format_err_line("────────────────");
    }

    auto handle_backtrace_success(Immutable_View<Stack_Frame> const frames) -> void
    {
      auto print_detailed_stack_frame {
        [i = 0](Stack_Frame const &frame) mutable {
          console().format_err_line("• #{}: {}", i, frame);
          ++i;
        }
      };

      console().format_err_line("BACKTRACE");
      console().format_err_line("─────────");

      iterate(frames)
        .examine(print_detailed_stack_frame)
        .consume();

      console().format_err_line("");
    }
  }

  auto handle_terminate() -> void
  {
    console().format_err_line("");

    auto const exception { std::current_exception() };

    try {
      if (exception) {
        std::rethrow_exception(exception);
      }
    } catch (std::exception const &e) {
      String_View const what { e.what(), std::strlen(e.what()) };

      console().format_err_line("UNCAUGHT EXCEPTION");
      console().format_err_line("──────────────────");
      console().format_err_line("• what(): {}", what);
      console().format_err_line("");
    }

    backtrace()
      .resolve(handle_backtrace_failure, handle_backtrace_success);

    std::abort();
  }
}