Wrap the code that might panic in std::panic::catch_unwind, passing a closure that returns a Result to capture the panic payload. This function returns Ok with the closure's result if no panic occurs, or Err with the panic payload if it does.
use std::panic;
fn main() {
let result: Result<(), &str> = panic::catch_unwind(|| {
// Code that might panic
panic!("Something went wrong");
});
match result {
Ok(_) => println!("No panic occurred"),
Err(payload) => println!("Caught a panic: {:?}", payload),
}
}
Note: The closure passed to catch_unwind must return a type that implements Send + 'static. If you need to catch panics from non-Send types, use catch_unwind(AssertUnwindSafe(...)).