Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way to propagate panics in tokio tasks?

Right now my panics are being swallowed. In my use case, I would like it to crash entire program and also print the stack trace. How should I configure it?

like image 253
user855 Avatar asked Dec 16 '25 13:12

user855


1 Answers

Panics are generally not swallowed, instead they are returned as an error when awaiting the tokio::task::JoinHandle returned from tokio::task::spawn() or tokio::task::spawn_blocking() and can be handled accordingly.

If a panic occurs within the Tokio runtime an error message is printed to stderr like this: "thread 'tokio-runtime-worker' panicked at 'Panicking...', src\main.rs:26:17". If you run the binary with the environment variable RUST_BACKTRACE set to 1 a stacktrace is printed as well.

As with all Rust programs you can set your own panic handler with std::panic::set_hook() to make it exit if any thread panics after printing the panic info like this:

let default_panic = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
    default_panic(info);
    std::process::exit(1);
}));
like image 188
HHK Avatar answered Dec 19 '25 06:12

HHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!