Search code examples
rustrust-cargopanic

Disable "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace" message


How to disable 'note: run with RUST_BACKTRACE=1 environment variable to display a backtrace' when panic in Rust? My code:

use std::{env, fs, path::Path};
fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() != 3{
        panic!("Incorrect args!");
    }
    let query: &String = &args[1];
    let path: &Path = Path::new(&args[2]);
    println!("Search: \"{query}\"\nPath: \"{}\"", path.to_str().unwrap());
    match path.exists(){
        true => (),
        false => {panic!("Invalid file path!");}
    }
    println!("Success");
}


Solution

  • While I largely agree with the comments/answers saying "don't", I do think there are situations where it would make sense to customize the output of a panic!

    For example, if you're making a user-facing CLI, you'd maybe want to add some extra info telling the user where to report the crash.

    When a thread panics, Rust calls a piece of code called the 'panic hook', which, by default, prints the run with RUST_BACKTRACE=1 text (plus the actual backtrace, if you have that variable set).

    You can override this default hook with a function/closure of your own via std::panic::set_hook:

    std::panic::set_hook(Box::new(|_| {
        println!("My cool panic output");
    }));