Sub topic 11
Recovering concrete errors with downcasting
This chapter assumes you can write a thiserror enum, return anyhow::Result from application code, and add context with Context. Earlier chapters covered those. Here you learn how to get a concrete error type back out of an anyhow::Error, and when you should not.
Why downcasting exists
anyhow::Error erases the type of the error it holds. A function returning anyhow::Result<u16> might have failed with a ConfigError, an std::io::Error, or a plain message. The caller sees only one type.
Most callers only print the error, and that is fine. Sometimes a caller must react to a specific failure. For example, a missing config file can mean "use defaults", while a permission error should abort. Downcasting lets you ask an anyhow::Error whether it holds a particular type and, if so, borrow or take that value.
The downcasting methods
anyhow::Error provides four methods for this.
| Method | Receiver | Returns | Use it when |
|---|---|---|---|
| `is::<T>()` | `&self` | `bool` | You only need a yes or no answer |
| `downcast_ref::<T>()` | `&self` | `Option<&T>` | You want to inspect the error and keep the original |
| `downcast_mut::<T>()` | `&mut self` | `Option<&mut T>` | You need to modify the held error (rare) |
| `downcast::<T>()` | `self` | `Result<T, anyhow::Error>` | You want ownership of the concrete value |
The type T must be Display + Debug + Send + Sync + 'static. Every thiserror type that holds only owned data meets this. An error type that borrows data with a non-'static lifetime does not, so you cannot downcast to it.
The Err case of downcast hands the original anyhow::Error back. Nothing is lost when the type does not match, so you can pass it along.
A worked example
The program below defines a thiserror enum, wraps its errors with context, and then recovers the concrete type.
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 lookup(key: &str) -> Result<u16, ConfigError> {
match key {
"port" => Ok(" 8080 ".trim().parse::<u16>()?),
"bad" => Ok("abc".parse::<u16>()?),
_ => Err(ConfigError::Missing(key.to_string())),
}
}
fn load(key: &str) -> Result<u16> {
let port = lookup(key).with_context(|| format!("loading {key}"))?;
Ok(port)
}
fn report(err: &anyhow::Error) {
for cause in err.chain() {
eprintln!("- {cause}");
}
if let Some(ConfigError::Missing(key)) = err.downcast_ref::<ConfigError>() {
eprintln!("hint: add `{key}` to the config file");
}
}
fn main() {
for key in ["port", "host", "bad"] {
match load(key) {
Ok(port) => println!("{key} = {port}"),
Err(err) => report(&err),
}
}
}Running it prints port = 8080 on standard output. For host, standard error shows the chain and the hint:
- loading host
- missing key: host
hint: add `host` to the config fileFor bad, the chain has three entries (loading bad, invalid port, invalid digit found in string). No hint appears, because the downcast succeeds but the variant is InvalidPort, not Missing.
Notice that downcast_ref::<ConfigError>() worked even though with_context had wrapped the error in a message. This is deliberate. anyhow lets you downcast to the original error type and also to the type of the context value.
What downcasting can and cannot see
This is where most mistakes happen. anyhow downcasting inspects the outermost layer of the error: the error you put in, plus any context attached with .context(). It does not search the source() chain.
Suppose a library defines AppError::Config(#[from] ConfigError), and your code converts an AppError into anyhow::Error with ?. The anyhow::Error now holds an AppError. Calling downcast_ref::<ConfigError>() returns None, even though a ConfigError sits one level down.
To find a type that may be anywhere in the chain, walk the chain yourself. Each item from chain() is a &(dyn std::error::Error + 'static), and that type has its own downcast_ref method.
use anyhow::Error;
use std::io;
fn find_io_error(err: &Error) -> Option<&io::Error> {
err.chain().find_map(|cause| cause.downcast_ref::<io::Error>())
}
fn is_not_found(err: &Error) -> bool {
find_io_error(err).is_some_and(|e| e.kind() == io::ErrorKind::NotFound)
}For the common case of "what was the original failure", err.root_cause() returns the innermost error. It is also a dyn Error + 'static, so err.root_cause().downcast_ref::<io::Error>() works. Prefer chain().find_map when the type you want might not be the innermost cause.
Taking ownership with downcast
Use downcast when you want to consume the error, for example to move a String out of a variant or to convert it into another type.
use anyhow::Result;
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
}
fn fetch(key: &str) -> Result<u16> {
Err(ConfigError::Missing(key.to_string()).into())
}
fn port_or_default(key: &str) -> Result<u16> {
match fetch(key) {
Ok(port) => Ok(port),
Err(err) => match err.downcast::<ConfigError>() {
Ok(ConfigError::Missing(_)) => Ok(3000),
Err(other) => Err(other),
},
}
}
fn main() -> Result<()> {
println!("port = {}", port_or_default("port")?);
Ok(())
}The inner match has two arms. On a match, you own the ConfigError and handle it. On a mismatch, other is the untouched anyhow::Error, which you return as is. Because ConfigError has a single variant here, the first arm is exhaustive. With more variants you would add arms for the others, or a catch-all that rewraps the value with .into().
If you only need to read the error and then return it, downcast_ref is simpler. It avoids the rewrapping step.
use anyhow::{Context, Result};
use std::io::{self, ErrorKind};
fn read_optional(path: &str) -> Result<Option<String>> {
match std::fs::read_to_string(path).with_context(|| format!("failed to read {path}")) {
Ok(text) => Ok(Some(text)),
Err(err) => {
let not_found = err
.downcast_ref::<io::Error>()
.is_some_and(|e| e.kind() == ErrorKind::NotFound);
if not_found {
Ok(None)
} else {
Err(err)
}
}
}
}The is_some_and call ends the borrow of err before the if, so returning Err(err) compiles without trouble.
Common errors
- Forgetting that
?converts. If a function returnsResult<T, ConfigError>and you call it from ananyhowfunction with?, the error becomes ananyhow::Errorholding theConfigError. Downcast toConfigError, not toanyhow::Error. - Downcasting to the wrong layer. A
ConfigErrorstored as the#[source]of another error is not reachable withdowncast_refon theanyhow::Error. Usechain().find_map(...). - Matching on
Displaystrings.err.to_string().contains("missing")breaks when someone rewords a message. Downcast to a variant instead. - Assuming a downcast always succeeds. Both
downcast_refanddowncastcan fail. Handle theNoneorErrcase, usually by propagating the original error. - Downcasting to a type your dependency hides. A library may change which concrete error it returns. Downcasting to its internal types ties your code to its implementation. Check whether the library documents the type before you rely on it.
When not to downcast
Downcasting is a runtime check. The compiler cannot tell you that you forgot a variant, and it cannot warn you when a function stops returning the type you test for. If a function's callers regularly need to branch on the failure, that function should return its own typed error instead of anyhow::Error.
| Situation | Better choice |
|---|---|
| One or two call sites react to a specific error, in application code | `downcast_ref` |
| Many callers must branch on the failure | Return a `thiserror` enum from that function |
| You are writing a library | Return a typed error, and never make users downcast |
| You need to test which error was returned | Test the typed function directly with `matches!` |
| You only want to show the cause to a human | Print the chain, no downcast needed |
A practical pattern is to keep anyhow at the top of the program, and keep typed errors in the lower layers where the decisions are made. The lower function returns Result<T, ConfigError>. The top-level function converts with ? and does not need to downcast at all, because the branching already happened lower down.
Summary
is,downcast_ref,downcast_mut, anddowncastrecover a concrete type from ananyhow::Error.- They see the outermost error and any context type, but not the
source()chain. - Use
chain().find_map(|c| c.downcast_ref::<T>())orroot_cause()to reach deeper layers. - Use downcasting sparingly in application code, and return typed errors when callers need to branch.
Exercise
A library function returns Result<(), AppError>, where AppError is a thiserror enum with a variant Io(#[from] std::io::Error). Your application calls it with ? inside a function returning anyhow::Result<()>. You then call err.downcast_ref::<std::io::Error>() on the resulting anyhow::Error, and it returns None even though the underlying failure was an I/O error. Why, and how do you fix it?
Show answer
The anyhow::Error holds an AppError, not an io::Error. downcast_ref checks only the outermost error and its context, so it does not look at AppError's source(). The io::Error is one layer down. To find it, walk the chain: err.chain().find_map(|c| c.downcast_ref::<std::io::Error>()). You could also match err.downcast_ref::<AppError>() first and read the Io variant. If many callers need this, the better fix is to have that layer return AppError and match on it directly.
Exercise
Write the body of fn needs_retry(err: &anyhow::Error) -> bool that returns true when any error in the chain is an std::io::Error with kind TimedOut.
Show answer
err.chain().any(|cause| cause.downcast_ref::<std::io::Error>().is_some_and(|e| e.kind() == std::io::ErrorKind::TimedOut)). Using chain() makes the check work even when the I/O error is wrapped in context or in another error type's source().