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!"),
}
}
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!
You need to register a panic hook with
std::panic::set_hook
that does nothing. You can then catch it withstd::panic::catch_unwind
: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:
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.