kaspa_core/
panic.rs

1use kaspa_core::error;
2use std::{panic, process, thread};
3
4/// Configures the panic hook to exit the program on every panic
5pub fn configure_panic() {
6    let default_hook = panic::take_hook();
7    panic::set_hook(Box::new(move |panic_info| {
8        // Get the panic location details
9        let (file, line, column) = match panic_info.location() {
10            Some(location) => (location.file(), location.line(), location.column()),
11            None => ("unknown", 0, 0),
12        };
13
14        let message = match panic_info.payload().downcast_ref::<&str>() {
15            Some(s) => *s,
16            None => match panic_info.payload().downcast_ref::<String>() {
17                Some(s) => &s[..],
18                None => "Box<dyn Any>",
19            },
20        };
21        // Get the thread name
22        let current_thread = thread::current();
23        let thread_name = current_thread.name().unwrap_or("<unnamed>");
24        // Log the panic
25        error!("thread '{}' panicked at {}:{}:{}: {}", thread_name, file, line, column, message);
26        // Invoke the default hook as well, since it might include additional info such as the full backtrace
27        default_hook(panic_info);
28        println!("Exiting...");
29        process::exit(1);
30    }));
31}