Last active
May 8, 2024 14:41
-
-
Save thewh1teagle/509f2d73131c621758c236dbc168967f to your computer and use it in GitHub Desktop.
catch panics in rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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