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!
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:
Use following catch_unwind_silent
instead of regular catch_unwind
to achieve silence for expected exceptions:
use std::panic;
fn catch_unwind_silent<F: FnOnce() -> R + panic::UnwindSafe, R>(f: F) -> std::thread::Result<R> {
let prev_hook = panic::take_hook();
panic::set_hook(Box::new(|_| {}));
let result = panic::catch_unwind(f);
panic::set_hook(prev_hook);
result
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With