Suppress panic output in Rust when using panic::ca

2019-06-16 09:01发布

I'm using panic::catch_unwind to catch a panic:

use std::panic;

fn main() {
    let result = panic::catch_unwind(|| {
        panic!("test panic");
    });

    match result {
        Ok(res) => res,
        Err(_) => println!("caught panic!"),
    }
}

(Playground)

This seems to work just fine, but I am still getting the output of the panic to stdout. I'd like this to only print out:

caught panic!

Instead of

thread '<main>' panicked at 'test panic', <anon>:6
note: Run with `RUST_BACKTRACE=1` for a backtrace.
caught panic!

2条回答
聊天终结者
2楼-- · 2019-06-16 10:03

You need to register a panic hook with std::panic::set_hook that does nothing. You can then catch it with std::panic::catch_unwind:

use std::panic;

fn main() {
    panic::set_hook(Box::new(|_info| {
        // do nothing
    }));

    let result = panic::catch_unwind(|| {
        panic!("test panic");
    });

    match result {
        Ok(res) => res,
        Err(_) => println!("caught panic!"),
    }
}

As Matthieu M. notes, you can get the current hook with std::panic::take_hook in order to restore it afterwards, if you need to.

See also:

查看更多
地球回转人心会变
3楼-- · 2019-06-16 10:06

You can use std::panic::set_hook to suppress the output. Note however that the hook is process-global and it will suppress reporting on all panics that may occur within the program.

As already plugged in my answer to a similar question, I've written a crate that provides a way to suppress the hook with composable filters, including one that works on a per-thread basis.

查看更多
登录 后发表回答