What happens when an async task panics?

When an async task panics, what is the right behavior ?

  1. kill just the task; nothing else affected

  2. kills entire program

  3. undefined behavior


Never on purpose in Rust.

IIRC, usually one of two things happen:

  1. Either a worker thread under the threadpool of whatever runtime you're using will panic, print its last dying message, and simply be replaced by the runtime.
  2. Or, the thread will have its contents be wrapped inside of a std::panic::catch_unwind, which will then print the panic message.

After which, it's up to the runtime as to whether the whole program fails or not.

1 Like

Actually three.

  1. The binary is compiled with panic = "abort" mode, so the whole process is getting terminated. This is easier way to handle unexpected errors if the application already is fail safe/horizontally scaled. Usually the process will be re-launched by external mechanisms like systemd.

In tokio:

Again, like std::thread 's JoinHandle type, if the spawned task panics, awaiting its JoinHandle will return a JoinError `.

Per tokio::task - Rust

What the right behavior is for your application will depend on the application. For example, a web server would probably want the first behavior, but I can also imagine cases that want the second.

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.