Panic in Tokio task does not end the program execution

Hey all, I'm using Tokio with the #[tokio::main] attribute. When a panic occurs I noticed that the current panicking task will end but the program is still running. I assume that is because other tasks are running. I'm using tokio::spawn to start new async tasks.

I would like the entire program to end as soon as any panic occurs. I plan on having long running programs doing some calculations and I need the process to exit with an error code as soon as possible.

Is there any way of doing this ? Am I missing something here ?

It is completely analogous to how threads spawned with std::thread::spawn also prevent panics from crashing the program.

The most direct way of causing any panic to end the program is to configure them to abort the process instead of unwinding the stack. Otherwise, you will have to somehow propagate them up and terminate the program.

1 Like

Yeah I thought more about it and figured that is should probably keep the same behaviour as threads. Will try and look at catching the unwinding.

FYI I just added a

    std::panic::catch_unwind(|| {
        do_stuff();
    }).unwrap();

block on top of my tasks. Just so my process ends as soon as possible to save some cloud minutes in case something goes wrong :stuck_out_tongue:

You can compile your binary with panic = "abort" option to not even generate stack unwind code.

https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/aborting-on-panic.html

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.