Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress panic output in Rust when using panic::catch_unwind

Tags:

exception

rust

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!
like image 576
Matt Avatar asked Feb 22 '16 16:02

Matt


3 Answers

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:

  • Redirect panics to a specified buffer
like image 180
Shepmaster Avatar answered Nov 07 '22 18:11

Shepmaster


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
}
like image 7
k06a Avatar answered Nov 07 '22 17:11

k06a


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.

like image 1
mzabaluev Avatar answered Nov 07 '22 16:11

mzabaluev