Sub topic 11
Recovering concrete errors with downcasting
This chapter assumes you can define a thiserror enum and return anyhow::Result from a function. It also assumes you know how .context(...) adds a message.
Why downcasting exists
anyhow::Error erases the type of the error it holds. A function returning anyhow::Result<T> could be carrying an io::Error, a ParseIntError, or your own ConfigError. Most of the time you only print it. Sometimes the program must react to one specific failure, such as showing a hint for a missing key. Downcasting asks the erased error whether it is really a given type.
The downcast methods
| Method | Receives | Returns |
|---|---|---|
| `is::<T>()` | `&self` | `bool` |
| `downcast_ref::<T>()` | `&self` | `Option<&T>` |
| `downcast_mut::<T>()` | `&mut self` | `Option<&mut T>` |
| `downcast::<T>()` | `self` | `Result<T, anyhow::Error>` |
downcast consumes the error. If the type does not match, it gives the original error back in Err, so you can keep propagating it.
A complete example
The function below attaches context to a typed error. The caller then recovers the typed error.
use anyhow::{Context, Result};
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("invalid port")]
InvalidPort(#[from] std::num::ParseIntError),
}
fn get_port(input: Option<&str>) -> Result<u16> {
let raw = input
.ok_or_else(|| ConfigError::Missing("port".to_string()))
.context("loading server settings")?;
let port = raw
.trim()
.parse::<u16>()
.map_err(ConfigError::from)
.context("loading server settings")?;
Ok(port)
}
fn main() {
for input in [Some("8080"), None, Some("abc")] {
match get_port(input) {
Ok(port) => println!("port {port}"),
Err(err) => match err.downcast_ref::<ConfigError>() {
Some(ConfigError::Missing(key)) => {
println!("hint: add `{key}` to the config file");
}
Some(ConfigError::InvalidPort(_)) => {
println!("hint: the port must be between 0 and 65535");
}
None => println!("unexpected error: {err:#}"),
},
}
}
}This prints port 8080, then the missing-key hint, then the invalid-port hint.
The .context(...) call did not hide ConfigError. anyhow lets you downcast to the original error type, and also to the context type, even after you add context. The None arm covers every other failure, so the program still reports errors it did not expect.
Downcasting does not search the source chain
A common mistake is expecting downcast_ref to find an error buried in source(). It only checks the error anyhow holds, plus any context added with .context(...). Suppose your own enum wraps an io::Error with #[source], and that enum is the one anyhow holds. Then err.downcast_ref::<io::Error>() returns None.
To search the whole chain, walk it with chain(). Each item is a &dyn Error, which has its own downcast_ref.
use std::io;
fn find_io_error(err: &anyhow::Error) -> Option<&io::Error> {
err.chain().find_map(|cause| cause.downcast_ref::<io::Error>())
}You can then check io::ErrorKind::NotFound to decide whether to create a default file.
Owned downcasts
When you need the value itself, use downcast. It moves the error out. On a mismatch you get the original back, so you can return it unchanged.
fn handle(err: anyhow::Error) -> anyhow::Result<String> {
match err.downcast::<ConfigError>() {
Ok(ConfigError::Missing(key)) => Ok(format!("default for {key}")),
Ok(other) => Err(other.into()),
Err(original) => Err(original),
}
}When to avoid downcasting
Downcasting turns a compile-time guarantee into a runtime check. If you add a variant, the compiler will not point at the places that should handle it. These rules help:
- If callers must branch on failures, return the typed
thiserrorenum from that function instead ofanyhow::Result. A plainmatchis checked by the compiler. - Use downcasting at the edge of the application, such as
mainor a request handler, to choose exit codes, HTTP statuses, or hints. - Downcast to the narrowest type that matters. Avoid long ladders of
downcast_refcalls. Many of them suggest the function should return an enum.
Exercise
A function returns anyhow::Result<()>. It fails with a ConfigError::Missing, wrapped by a thiserror type AppError::Config that stores it with #[source]. anyhow holds the AppError. Does err.downcast_ref::<ConfigError>() find the ConfigError? If not, how do you get it?
Show answer
No. downcast_ref checks only the type anyhow holds, which is AppError, plus any .context(...) layers. The ConfigError sits in the source() chain. Use err.chain().find_map(|c| c.downcast_ref::<ConfigError>()).