liveBook · Manning

Panic hook

As explained in Learn Rust in a Month of Lunches

A panic hook is a globally registered callback invoked when a Rust panic occurs before the runtime performs its panic strategy.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains registration, PanicInfo, payload downcasting, removal, and abort interaction through focused examples.
Examples
Uses panic!, unwrap on an invalid parse, custom messages, payload inspection, hook removal, and database shutdown handling.
What you can do after
Operate/configure the standard library to replace, inspect, and remove a global panic hook.
How it connects
Connects panic hooks with PanicInfo, payloads, backtraces, stack unwinding, abort behavior, and the Any trait.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.