Vanello1908
Vanello1908

Reputation: 15

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");
}

Upvotes: 0

Views: 5846

Answers (2)

Joe Clay
Joe Clay

Reputation: 35837

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");
}));

Upvotes: 7

cafce25
cafce25

Reputation: 27549

Just don't use panic! for things it's not designed for, it is for states that can't happen unless you have a bug in your program, if you want to signal an expected error condition, you can use a Result in main like you're supposed to anyways:

use std::{env, fs, path::Path};
fn main() -> Result<(), &'static str> {
    let args: Vec<String> = env::args().collect();
    if args.len() != 3 {
        return Err("Incorrect args!");
    }
    let query: &String = &args[1];
    let path: &Path = Path::new(&args[2]);
    println!("Search: \"{query}\"\nPath: \"{}\"", path.display());
    if !path.exists() {
        return Err("Invalid file path!");
    }
    println!("Success");
    Ok(())
}

Upvotes: 6

Related Questions