Skip to content

Instantly share code, notes, and snippets.

@thewh1teagle
Last active May 8, 2024 14:41
Show Gist options
  • Save thewh1teagle/509f2d73131c621758c236dbc168967f to your computer and use it in GitHub Desktop.
Save thewh1teagle/509f2d73131c621758c236dbc168967f to your computer and use it in GitHub Desktop.
catch panics in rust
fn main() {
// Set up a panic hook to print the backtrace
std::panic::set_hook(Box::new(|info| {
let mut message = String::new();
message.push_str(&format!("thread '{}' ", std::thread::current().name().unwrap_or("unknown")));
message.push_str(&format!("{}", info));
if let Ok(var) = std::env::var("RUST_BACKTRACE") {
if var == "1" {
let backtrace = std::backtrace::Backtrace::capture();
message.push_str(&format!("{}", backtrace));
}
}
eprintln!("{}", message)
// do whatever with the message
}));
panic!("Oh no!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment