Skip to main content

bee_tui/
errors.rs

1use std::env;
2
3use tracing::error;
4
5pub fn init() -> color_eyre::Result<()> {
6    let (panic_hook, eyre_hook) = color_eyre::config::HookBuilder::default()
7        .panic_section(format!(
8            "This is a bug. Consider reporting it at {}",
9            env!("CARGO_PKG_REPOSITORY")
10        ))
11        .capture_span_trace_by_default(false)
12        .display_location_section(false)
13        .display_env_section(false)
14        .into_hooks();
15    eyre_hook.install()?;
16    std::panic::set_hook(Box::new(move |panic_info| {
17        if let Ok(mut t) = crate::tui::Tui::new() {
18            if let Err(r) = t.exit() {
19                error!("Unable to exit Terminal: {:?}", r);
20            }
21        }
22
23        #[cfg(not(debug_assertions))]
24        {
25            use human_panic::{handle_dump, metadata, print_msg};
26            let metadata = metadata!();
27            let file_path = handle_dump(&metadata, panic_info);
28            // prints human-panic message
29            print_msg(file_path, &metadata)
30                .expect("human-panic: printing error message to console failed");
31            eprintln!("{}", panic_hook.panic_report(panic_info)); // prints color-eyre stack trace to stderr
32        }
33        let msg = format!("{}", panic_hook.panic_report(panic_info));
34        error!("Error: {}", strip_ansi_escapes::strip_str(msg));
35
36        #[cfg(debug_assertions)]
37        {
38            // Better Panic stacktrace that is only enabled when debugging.
39            better_panic::Settings::auto()
40                .most_recent_first(false)
41                .lineno_suffix(true)
42                .verbosity(better_panic::Verbosity::Full)
43                .create_panic_handler()(panic_info);
44        }
45
46        std::process::exit(libc::EXIT_FAILURE);
47    }));
48    Ok(())
49}
50
51/// Similar to the `std::dbg!` macro, but generates `tracing` events rather
52/// than printing to stdout.
53///
54/// By default, the verbosity level for the generated events is `DEBUG`, but
55/// this can be customized.
56#[macro_export]
57macro_rules! trace_dbg {
58        (target: $target:expr, level: $level:expr, $ex:expr) => {
59            {
60                match $ex {
61                        value => {
62                                tracing::event!(target: $target, $level, ?value, stringify!($ex));
63                                value
64                        }
65                }
66            }
67        };
68        (level: $level:expr, $ex:expr) => {
69                trace_dbg!(target: module_path!(), level: $level, $ex)
70        };
71        (target: $target:expr, $ex:expr) => {
72                trace_dbg!(target: $target, level: tracing::Level::DEBUG, $ex)
73        };
74        ($ex:expr) => {
75                trace_dbg!(level: tracing::Level::DEBUG, $ex)
76        };
77}