A panic hook is a globally registered callback that runs when Rust encounters a panic, before the runtime continues with its panic strategy. By default, Rust reports the panicking thread, message or error, source location, and a backtrace hint. Calling set_hook replaces that default behavior with a closure of your choice. section 21.2
Replace the default message
Register a closure with set_hook and print a friendlier message: std::panic::set_hook(Box::new(|info| { println!("Something went wrong: {info}"); })); panic!(); The closure receives PanicInfo, so formatting info preserves useful panic details. Its payload can also be inspected and downcast, commonly to &str or String. Because the hook is global, it affects later panics in the process. section 21.2
A panic hook can be adjusted in several practical ways:
- Print a custom message instead of the default location and error information. section 21.2
- Use the PanicInfo argument to display the original panic information. section 21.2
- Call take_hook to remove the current hook and retrieve it; modifying the hook from a panicking thread itself causes another panic. section 21.2
- Combine hook handling with panic = 'abort' when choosing a smaller release binary instead of stack unwinding. section 21.6
fn main() {
std::panic::set_hook(Box::new(|_| {
println!("Oops, that didn't work.");
println!("앗 뭔가 잘못 됐네요."); #1
}));
panic!();
}
See a minimal runnable hook that replaces the standard panic message with custom output. section 21.2
