Sub topic 8
Collecting results and handling task panics
This chapter assumes you can spawn tasks with tokio::spawn, that you understand Send + 'static bounds, and that you know the basics of Result and ? in Rust. Here you will learn what a JoinHandle gives you, how task failures surface, and how to collect results from many tasks.
What a JoinHandle is
tokio::spawn returns a JoinHandle<T>, where T is the output type of the spawned future. The handle is itself a future. Awaiting it yields Result<T, JoinError>.
There are two layers of outcome:
- The outer
Resulttells you whether the task ran to completion. It fails with aJoinErrorif the task panicked or was cancelled. - The inner value
Tis whatever your task returned. If the task returns its ownResult, you get a nestedResult<Result<_, _>, JoinError>.
use tokio::task::JoinError;
async fn work() -> Result<u32, String> {
Ok(7)
}
#[tokio::main]
async fn main() -> Result<(), JoinError> {
let handle = tokio::spawn(work());
// Outer `?` handles JoinError, inner match handles our own error.
match handle.await? {
Ok(n) => println!("task succeeded with {n}"),
Err(e) => println!("task failed on its own terms: {e}"),
}
Ok(())
}Keeping the two layers separate matters. A JoinError means the task did not finish normally. An inner Err means your code ran and chose to report a failure.
Dropping a handle detaches the task
Dropping a JoinHandle does not cancel the task. The task keeps running in the background, and its result is discarded. This is different from dropping an ordinary future, which stops it.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let _ = tokio::spawn(async {
sleep(Duration::from_millis(50)).await;
println!("still ran after the handle was dropped");
});
// Give the detached task time to finish before main exits.
sleep(Duration::from_millis(200)).await;
}If main returns first, the runtime shuts down and detached tasks are dropped without finishing. Keep the handle and await it whenever you need the work to complete.
What happens when a task panics
A panic inside a spawned task is caught by the runtime. It does not unwind into the code that spawned the task, and it does not take down other tasks or worker threads. The panic message is still printed to stderr by the default panic hook. The panic is reported to whoever awaits the handle as a JoinError.
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
let v: Vec<u32> = Vec::new();
v[3] // index out of bounds: panics
});
match handle.await {
Ok(value) => println!("got {value}"),
Err(e) if e.is_panic() => println!("task panicked"),
Err(e) if e.is_cancelled() => println!("task was cancelled"),
Err(e) => println!("other join error: {e}"),
}
}JoinError has two states you can test for:
| Method | True when |
|---|---|
| `is_panic()` | The task panicked. |
| `is_cancelled()` | The task was aborted with `JoinHandle::abort` or dropped by runtime shutdown. |
If the panic was raised by a regular panic! call, the compiled binary must use the default panic = "unwind" setting. With panic = "abort" in Cargo.toml, a panic terminates the whole process and no JoinError is ever produced.
Recovering the panic payload
JoinError::into_panic returns the boxed payload (Box<dyn Any + Send>). It panics if the error is not a panic, so check is_panic() first. You can pass the payload to std::panic::resume_unwind to re-raise the panic in the awaiting task, or downcast it to read the message.
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
if true {
panic!("database connection lost");
}
1u32
});
if let Err(e) = handle.await {
if e.is_panic() {
let payload = e.into_panic();
let msg = payload
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown panic".to_string());
println!("recovered message: {msg}");
}
}
}A literal message passed to panic! is a &'static str. A formatted message is a String. That is why the example tries both downcasts.
Cancelling with abort
JoinHandle::abort asks the runtime to cancel the task. The task stops at its next .await point, and awaiting the handle then returns a JoinError for which is_cancelled() is true.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_secs(60)).await;
});
handle.abort();
let err = handle.await.unwrap_err();
println!("cancelled: {}", err.is_cancelled());
}Abort only takes effect when the task yields. A task stuck in a loop with no .await cannot be aborted. A task that already finished before abort was called still returns its normal result. Cancellation is covered in more depth in a later chapter.
Collecting results from many tasks
A common pattern is to spawn a batch of tasks and gather every result. The simplest form stores the handles in a Vec and awaits them in order.
use std::time::Duration;
use tokio::time::sleep;
async fn square(n: u64) -> u64 {
sleep(Duration::from_millis(50)).await;
n * n
}
#[tokio::main]
async fn main() {
let handles: Vec<_> = (1..=5).map(|n| tokio::spawn(square(n))).collect();
let mut results = Vec::new();
for h in handles {
results.push(h.await.unwrap());
}
println!("{results:?}");
}All five tasks start running as soon as they are spawned. Awaiting them one by one only controls the order in which you read results, so the total time is about 50 ms, not 250 ms. Results keep the order of the handles, regardless of which task finished first.
Using unwrap here makes any panic in a child task crash the caller. In services you usually want to decide per task instead.
Handling each outcome
This version separates successes, task errors and panics without stopping at the first problem.
async fn parse(input: &'static str) -> Result<i32, std::num::ParseIntError> {
if input == "boom" {
panic!("unexpected input");
}
input.parse::<i32>()
}
#[tokio::main]
async fn main() {
let inputs = ["10", "abc", "boom", "30"];
let handles: Vec<_> = inputs
.iter()
.map(|s| tokio::spawn(parse(s)))
.collect();
for (input, handle) in inputs.iter().zip(handles) {
match handle.await {
Ok(Ok(n)) => println!("{input}: parsed {n}"),
Ok(Err(e)) => println!("{input}: parse error: {e}"),
Err(e) if e.is_panic() => println!("{input}: task panicked"),
Err(e) => println!("{input}: join error: {e}"),
}
}
}Collecting in completion order with JoinSet
Awaiting a Vec of handles reads results in spawn order. If a slow first task delays everything, you cannot react to faster ones. tokio::task::JoinSet yields results as tasks finish.
use std::time::Duration;
use tokio::task::JoinSet;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let mut set = JoinSet::new();
for (i, delay) in [300u64, 100, 200].into_iter().enumerate() {
set.spawn(async move {
sleep(Duration::from_millis(delay)).await;
i
});
}
while let Some(res) = set.join_next().await {
match res {
Ok(i) => println!("task {i} finished"),
Err(e) => println!("task failed: {e}"),
}
}
}This prints task 1, then task 2, then task 0. join_next returns None when the set is empty.
JoinSet has one more property that raw handles lack: dropping a JoinSet aborts every task still inside it. This makes it a convenient scope for related work. When the owner goes away, the children are cleaned up instead of leaking.
| Feature | `Vec<JoinHandle>` | `JoinSet` |
|---|---|---|
| Result order | Spawn order | Completion order |
| Dropping the collection | Tasks keep running | Tasks are aborted |
| Abort everything | Loop over handles | `abort_all()` |
Common errors
- Unwrapping every handle.
handle.await.unwrap()turns a child panic into a panic in the parent. Match on theJoinErrorwhen failures must be isolated. - Confusing the two error layers.
?onhandle.awaitremoves only theJoinError. The innerResultstill needs handling. - Assuming a dropped handle cancels the task. It detaches the task. Use
abortor aJoinSetfor cancellation. - Calling
into_panicon a cancelled error. It panics. Checkis_panic()first. - Panics holding a
std::sync::Mutex. If a task panics while holding the guard, the mutex becomes poisoned and laterlock()calls returnErr. Keep critical sections short and decide how to treat poisoning. - Expecting abort to stop CPU loops. Cancellation needs an
.awaitto take effect.
Exercise
You spawn three tasks and store the handles in a Vec. Task 2 panics. You loop over the handles and call h.await.unwrap(). What happens to tasks 1 and 3, and what happens to your loop? How would you change the loop so that tasks 1 and 3 still report their results?
Show answer
Tasks 1 and 3 are unaffected, because the runtime catches the panic inside task 2. The loop, however, calls unwrap on the Err(JoinError) returned for task 2, so the awaiting task panics at that point, and results for any handle after it are never read. To keep going, match on each result instead: match h.await { Ok(v) => ..., Err(e) if e.is_panic() => ..., Err(e) => ... }. Each handle is then handled separately and the loop reaches every task.
Exercise
What is the difference between dropping a JoinHandle and dropping a JoinSet that contains running tasks?
Show answer
Dropping a JoinHandle detaches the task, which keeps running and whose result is discarded. Dropping a JoinSet aborts all tasks still in the set, so they are cancelled at their next .await point.