wiki_tui/
panic_handler.rs

1use crate::terminal::Tui;
2use anyhow::Result;
3use tracing::error;
4
5pub fn initialize_panic_handler() -> Result<()> {
6    #[allow(unused_variables)]
7    let (panic_hook, eyre_hook) = color_eyre::config::HookBuilder::default()
8        .display_location_section(true)
9        .display_env_section(true)
10        .into_hooks();
11
12    eyre_hook.install()?;
13
14    std::panic::set_hook(Box::new(move |panic_info| {
15        match Tui::new() {
16            Ok(mut tui) => {
17                if let Err(error) = tui.exit() {
18                    error!("unable to exit terminal: {error:?}");
19                }
20            }
21            Err(error) => error!("unable to exit terminal {error:?}"),
22        }
23
24        #[cfg(not(debug_assertions))]
25        {
26            eprintln!("{}", panic_hook.panic_report(panic_info));
27            use human_panic::{handle_dump, print_msg, Metadata};
28            let meta = Metadata::new(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
29                .authors(env!("CARGO_PKG_AUTHORS").replace(':', ", "))
30                .homepage(env!("CARGO_PKG_HOMEPAGE"));
31
32            let file_path = handle_dump(&meta, panic_info);
33            print_msg(file_path, &meta)
34                .expect("human-panic: printing error message to console failed");
35        }
36
37        #[cfg(debug_assertions)]
38        {
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
49    Ok(())
50}