Sub topic 11
Propagating errors with ? in async code
This chapter assumes you know Result, the ? operator and the From trait in ordinary Rust. It also assumes you can write async fn, use .await, and start a Tokio runtime. The chapter covers where ? returns to inside async code, how errors from timeouts and spawned tasks combine with your own, and the type-inference problem in async blocks.
`?` behaves the same in async functions
An async fn that returns Result<T, E> is a function whose future produces a Result<T, E>. The ? operator inside it works as in a normal function. On Err(e), it converts e with From and returns early from that function.
use tokio::fs;
async fn read_len(path: &str) -> std::io::Result<usize> {
let data = fs::read(path).await?;
Ok(data.len())
}
#[tokio::main]
async fn main() {
match read_len("Cargo.toml").await {
Ok(n) => println!("{n} bytes"),
Err(e) => println!("error: {e}"),
}
}Read fs::read(path).await? in two steps:
.awaitsuspends until the I/O finishes and produces aResult<Vec<u8>, io::Error>.?unwraps thatResultor returns the error.
The order matters. .await must come first, because ? cannot be applied to a future. Writing fs::read(path)? fails to compile, since a future is not a Result.
An early return through ? ends the future of read_len. It does not end the caller. The caller receives the Err as the output of its own .await and decides what to do with it.
Combining several error types
Real async functions mix errors from different sources: I/O, parsing, timeouts. The usual approach is one error enum with a From implementation for each source. Then ? converts each error automatically.
tokio::time::timeout shows this well. It wraps a future and returns Result<F::Output, Elapsed>. When the inner future is itself fallible, you get a nested Result, and you apply ? twice.
use std::fmt;
use std::time::Duration;
use tokio::fs;
use tokio::time::{error::Elapsed, timeout};
#[derive(Debug)]
enum AppError {
Io(std::io::Error),
Timeout,
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppError::Io(e) => write!(f, "io error: {e}"),
AppError::Timeout => write!(f, "timed out"),
}
}
}
impl std::error::Error for AppError {}
impl From<std::io::Error> for AppError {
fn from(e: std::io::Error) -> Self {
AppError::Io(e)
}
}
impl From<Elapsed> for AppError {
fn from(_: Elapsed) -> Self {
AppError::Timeout
}
}
async fn load(path: &str) -> Result<String, AppError> {
let bytes = timeout(Duration::from_secs(1), fs::read(path)).await??;
Ok(String::from_utf8_lossy(&bytes).into_owned())
}
#[tokio::main]
async fn main() {
match load("Cargo.toml").await {
Ok(text) => println!("{} chars", text.len()),
Err(e) => println!("failed: {e}"),
}
}In .await??, the first ? handles the Elapsed error from the deadline. The second handles the io::Error from the read. Each one uses a different From implementation.
When a deadline passes, timeout drops the inner future. Cleanup of that future happens through Drop, which the cancellation chapter covers.
Errors and spawned tasks
tokio::spawn adds one more layer. Awaiting a JoinHandle<T> gives Result<T, JoinError>. A JoinError means the task did not finish normally: it panicked or was cancelled. Your own errors live inside T, so a task that returns Result<U, E> produces Result<Result<U, E>, JoinError> when awaited.
use tokio::fs;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
#[tokio::main]
async fn main() -> Result<(), BoxError> {
let handle = tokio::spawn(async {
let data = fs::read("Cargo.toml").await?;
Ok::<usize, BoxError>(data.len())
});
let len = handle.await??;
println!("{len} bytes");
Ok(())
}Three details in this example are worth knowing:
Box<dyn Error + Send + Sync>accepts any error type that isError + Send + Sync + 'static. That includesio::ErrorandJoinError, so?converts both without custom code.- The
Sendbound is not optional here. A spawned task's output must beSend, so a bareBox<dyn Error>would not compile. TheSendand'staticchapter explains why. maincan returnResult<(), BoxError>. If it returnsErr, the process prints the error withDebugformatting and exits with a nonzero code.
You can inspect a JoinError with is_panic() and is_cancelled(). A panic inside a task does not crash the program. It only appears as an Err on that task's handle, so code that ignores handles will never see it.
The async block inference problem
An async fn states its return type in its signature. An async block does not, and the compiler often cannot infer the error type of a ? inside one.
If you write Ok(data.len()) as the last expression instead, the block's error type stays ambiguous and compilation fails. The same annotation also works for closures that return async blocks.
Running several fallible futures together
tokio::join! waits for all of its futures and returns a tuple of their outputs. When those outputs are Results, you must check each one afterwards. tokio::try_join! is the fallible version. It requires every future to return a Result with the same error type. It returns Ok with a tuple of the success values if all succeed. As soon as one future returns Err, it returns that error and drops the others.
use tokio::fs;
#[tokio::main]
async fn main() -> std::io::Result<()> {
let (a, b) = tokio::try_join!(fs::read("Cargo.toml"), fs::read("Cargo.lock"))?;
println!("{} {}", a.len(), b.len());
Ok(())
}The dropped futures are cancelled, which is usually what you want for all-or-nothing work. If you need every result even when some fail, use join! and handle each Result yourself.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `the ? operator can only be used in an async function that returns Result or Option` | The enclosing async fn or block returns `()`. | Return `Result`, or handle the error with `match`. |
| `type annotations needed` on an async block | The error type of `?` cannot be inferred. | Use `Ok::<T, E>(...)` at the end of the block. |
| `future cannot be sent between threads safely` | A non-`Send` error such as `Box<dyn Error>` crosses a spawn boundary. | Use `Box<dyn Error + Send + Sync>` or a concrete error type. |
| Task failure is never noticed | The `JoinHandle` was dropped without awaiting it. | Await the handle and apply `?` to both layers. |
Exercise
A task is spawned with tokio::spawn(async { parse().await }), where parse returns Result<u32, MyErr>. What is the type of handle.await, and how do you get the u32 in a function that returns Result<u32, MyErr>, assuming MyErr implements From<JoinError>?
Show answer
handle.await has type Result<Result<u32, MyErr>, JoinError>. The outer layer reports whether the task ran to completion, and the inner layer is the result of parse. With From<JoinError> implemented for MyErr, you write let n = handle.await??;. The first ? converts the JoinError and the second returns the MyErr.