Sub topic 10
Propagating errors with ? in async code
This chapter assumes you know Result, Option, and the ? operator in ordinary Rust. It also assumes you can write an async fn and .await it, and that you have Tokio in Cargo.toml with the "full" feature.
The ? operator works the same way
An async fn that returns Result<T, E> produces a future whose output is Result<T, E>. Inside the body, ? behaves exactly as it does in a normal function. If the value is Err, the function returns early with that error. If it is Ok, you get the inner value.
use tokio::fs;
async fn read_len(path: &str) -> std::io::Result<usize> {
let data = fs::read(path).await?;
Ok(data.len())
}Notice the order: .await comes first, then ?. The .await turns the future into a Result. The ? then unwraps that Result. Writing fs::read(path)? is a type error, because a future is not a Result.
Where the error appears
The error does not appear when you call read_len. Calling it only creates a future. The error comes out when you await that future.
#[tokio::main]
async fn main() {
let fut = read_len("missing.txt");
println!("future created, nothing has run yet");
match fut.await {
Ok(n) => println!("{n} bytes"),
Err(e) => println!("failed: {e}"),
}
}Combining different error types
Real functions often fail in more than one way. Each ? converts the error with From::from, so the function's error type must be something the other errors convert into. A boxed trait object is the quickest choice for small programs.
use std::error::Error;
use tokio::fs;
async fn parse_file(path: &str) -> Result<i64, Box<dyn Error>> {
let text = fs::read_to_string(path).await?; // io::Error
let n = text.trim().parse::<i64>()?; // ParseIntError
Ok(n)
}
#[tokio::main]
async fn main() {
match parse_file("number.txt").await {
Ok(n) => println!("{n}"),
Err(e) => println!("error: {e}"),
}
}Libraries usually define their own error enum instead, with a From implementation for each source error.
Errors from spawned tasks
A spawned task adds a second layer. Awaiting a JoinHandle gives Result<T, JoinError>. The JoinError means the task panicked or was cancelled. If the task itself returns a Result, you have two layers to handle.
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async { "42".parse::<i32>() });
match handle.await {
Ok(Ok(n)) => println!("parsed {n}"),
Ok(Err(e)) => println!("task returned an error: {e}"),
Err(e) => println!("task failed to finish: {e}"),
}
}Common mistakes
- Using
?inmainwithout a return type.mainmust return aResultfor?to compile. Writeasync fn main() -> Result<(), Box<dyn Error>>with#[tokio::main]. - Using
?in an async block with no known error type. The compiler cannot infer the error type. Add an annotation such asOk::<_, std::io::Error>(value)at the end of the block. - Ignoring the
JoinHandle. If you never await it, a task's error or panic goes unnoticed.
Exercise
What is wrong with let data = tokio::fs::read(path)?; inside an async fn, and how do you fix it?
Show answer
The call returns a future, not a Result, so ? cannot be applied to it. Await the future first, then apply ?: let data = tokio::fs::read(path).await?;.
Exercise
You write match handle.await { Ok(Ok(n)) => .., Ok(Err(e)) => .., Err(e) => .. } for a spawned task. What does each of the three arms mean?
Show answer
Ok(Ok(n)) means the task finished and its own Result was a success. Ok(Err(e)) means the task finished but returned its own error. Err(e) is a JoinError: the task panicked or was cancelled.