Sub topic 6
Application errors with anyhow::Result
This chapter assumes you can write a Result-returning function and use ?. It also assumes you have seen a hand-written or thiserror error enum, as in the previous chapters. Here you will learn what anyhow::Error is, why ? works with it, how it prints, and where it stops being the right choice.
The problem anyhow solves
A typed error enum like ConfigError is a good fit for a library, because callers can match on its variants. In a binary, the code that handles errors is often just main, which prints a message and exits. Writing one enum that lists every failure from every dependency (io::Error, ParseIntError, a JSON error, an HTTP error) adds code and no information.
The anyhow crate gives you one error type that can hold any error. Add it with cargo add anyhow.
What anyhow::Error is
anyhow::Error is a wrapper around a heap-allocated error. Internally it holds a pointer to a boxed value that implements std::error::Error + Send + Sync + 'static, plus an optional backtrace. It is one machine word wide, so Result<T, anyhow::Error> stays small on the success path.
The crate also defines an alias:
pub type Result<T, E = anyhow::Error> = core::result::Result<T, E>;So anyhow::Result<u16> means Result<u16, anyhow::Error>. The alias has a default for E, so you can still write anyhow::Result<u16, MyError> when you need a different error type.
Why ? just works
When you write expr? in a function that returns anyhow::Result, Rust calls From::from on the error. anyhow provides this implementation:
impl<E> From<E> for anyhow::Error
where
E: std::error::Error + Send + Sync + 'staticEvery standard error type, every thiserror type you define, and most third-party errors satisfy that bound. You can mix error types freely in one function.
use anyhow::Result;
use std::fs;
fn sum_numbers(path: &str) -> Result<i64> {
let text = fs::read_to_string(path)?; // io::Error becomes anyhow::Error
let mut total = 0;
for line in text.lines() {
total += line.trim().parse::<i64>()?; // ParseIntError becomes anyhow::Error
}
Ok(total)
}
fn main() -> Result<()> {
let total = sum_numbers("numbers.txt")?;
println!("total = {total}");
Ok(())
}If numbers.txt is missing, the program prints Error: No such file or directory (os error 2) to standard error and exits with status 1. This works because a main that returns Result<(), E> prints Error: {E:?} using the Debug format, and exits with a failure code when it gets an Err.
Using your own error types inside anyhow functions
anyhow does not replace thiserror. A function can call a library, or your own typed module, and pass the typed error upward with ?.
use anyhow::Result;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("invalid port")]
InvalidPort(#[from] std::num::ParseIntError),
}
fn parse_port(s: &str) -> Result<u16, ConfigError> {
Ok(s.trim().parse::<u16>()?)
}
fn start() -> Result<()> {
let port = parse_port("80x")?; // ConfigError becomes anyhow::Error
println!("port {port}");
Ok(())
}
fn main() {
if let Err(e) = start() {
eprintln!("{e}");
}
}Here parse_port uses the two-parameter form Result<u16, ConfigError>. This does not conflict with anyhow::Result because the use line imports a type alias with a default parameter. Writing a second argument overrides the default. The typed error survives inside the anyhow::Error, and the downcasting chapter shows how to get it back.
Three ways to print an anyhow error
The same error looks different depending on the format specifier. The example below uses .context(...), which wraps an error with a message. The next chapter covers it in detail.
use anyhow::{Context, Result};
fn read_port(text: &str) -> Result<u16> {
text.trim()
.parse::<u16>()
.context("could not read the port")
}
fn main() {
let err = read_port("abc").unwrap_err();
println!("{err}");
println!("{err:#}");
println!("{err:?}");
}The output is:
could not read the port
could not read the port: invalid digit found in string
could not read the port
Caused by:
invalid digit found in string| Format | What it prints | Typical use |
|---|---|---|
| `{}` | Only the outermost message | Short status lines, UI text |
| `{:#}` | The whole chain on one line, joined with `: ` | Log lines |
| `{:?}` | Outermost message, then a `Caused by:` list, then a backtrace if one was captured | Final report in `main` |
{:?} is what fn main() -> Result<()> uses. This is why the default report from a failing main already shows the full cause chain with no extra code.
Backtraces
On Rust 1.65 and later, anyhow captures a std::backtrace::Backtrace when an error is created, if the environment asks for one. Run your program with RUST_BACKTRACE=1 (or RUST_LIB_BACKTRACE=1) and the {:?} output gains a backtrace section. If a typed error inside already carries a backtrace, anyhow reuses it rather than capturing a second one.
RUST_BACKTRACE=1 cargo runCapturing a backtrace is not free. With the variable unset, the check is cheap and no backtrace is recorded. Use the variable while debugging, and consider leaving it off for code that creates many errors in a hot loop.
Why anyhow::Error does not implement Error
This surprises many learners. You cannot pass an anyhow::Error where a T: std::error::Error is required. The reason is coherence. If anyhow::Error implemented Error, the impl From<E> for anyhow::Error where E: Error would overlap with the standard library's blanket impl From<T> for T, and the compiler rejects overlapping impls.
Two practical effects follow:
- A function that returns
anyhow::Resultcannot itself be wrapped as the#[from]source of athiserrorvariant. Keepanyhowat the outer layer of the program. - If you need a
&dyn std::error::Errorfrom ananyhow::Error, useerr.as_ref(). It yields a&(dyn Error + Send + Sync + 'static), becauseanyhow::ErrorimplementsAsReffor that type.Box<dyn Error + Send + Sync>also has a conversion fromanyhow::Error.
The Send + Sync + 'static bound
The bound on From<E> is a common source of compile errors. A type can fail it in three ways:
| Failing property | Example | Fix |
|---|---|---|
| Not `Send` | An error holding an `Rc<str>` | Use `Arc<str>` or a `String` |
| Not `Sync` | An error holding a `Cell` or `RefCell` | Store plain data |
| Not `'static` | An error borrowing a `&str` from the input, or a `PoisonError<MutexGuard<'_, T>>` | Copy the data out, or map the error to a message |
For a poisoned mutex, map the error yourself. The value borrows the lock, so it cannot be converted with a bare ?:
use anyhow::{anyhow, Result};
use std::sync::Mutex;
fn read_counter(m: &Mutex<u32>) -> Result<u32> {
let guard = m.lock().map_err(|e| anyhow!("counter lock poisoned: {e}"))?;
Ok(*guard)
}The same issue affects Option. A None is not an error value, so opt? does not convert in an anyhow function that returns Result. Use .context("...") or .ok_or_else(|| anyhow!("...")). The macro anyhow! is covered in a later chapter.
anyhow::Error compared with Box<dyn Error>
You can approximate anyhow with Result<T, Box<dyn std::error::Error + Send + Sync>>. The comparison shows what the crate adds.
| Feature | `Box<dyn Error + Send + Sync>` | `anyhow::Error` |
|---|---|---|
| Accepts any `Error` through `?` | Yes | Yes |
| Accepts `&str` and `String` through `?` | Yes | No, use `anyhow!` or `bail!` |
| Adds context to an existing error | No | Yes, with `Context` |
| Captures a backtrace | No | Yes |
| Size of the error type | Two words (fat pointer) | One word |
| `Debug` output shows the cause chain | No | Yes |
The last row is the one you notice most. With Box<dyn Error> returned from main, you only see the top-level Debug output of the inner value.
When not to use anyhow
anyhow::Error erases the type. A caller can still try downcast_ref, but nothing in the signature tells them which errors to expect. This is the right trade in a binary and the wrong one in a library. A public function that returns anyhow::Result forces every user of your crate to guess its failure modes, and it ties your public API to the anyhow crate version. The chapter on choosing between thiserror and anyhow develops this rule.
A good middle path in a binary is to use typed errors in the modules where code needs to branch on the failure, and anyhow at the top level where code only reports it.
Common mistakes
- Using
?on anOption. The compiler reports that the?operator cannot convertOptionin a function returningResult. Add.context(...). - Using
?on aResult<T, String>.Stringdoes not implementError, so it cannot convert. Use.map_err(|e| anyhow!(e)). - Returning
anyhow::Resultfrom a library's public API. Callers lose the ability to match on variants. - Expecting
{}to show the cause. Plain{}shows only the outermost message. Use{:#}or{:?}.
Exercises
Exercise
A function returns anyhow::Result<()> and calls "x".parse::<u8>()? and std::fs::read("a.txt")?. Why does ? compile for both, even though the two errors have different types?
Show answer
Both ParseIntError and io::Error implement std::error::Error and are Send + Sync + 'static. That means the blanket impl From<E> for anyhow::Error applies to both, and ? calls it to convert each one into anyhow::Error.
Exercise
You print an anyhow::Error created with .context("loading settings") on top of an io::Error that says "permission denied". What does each of {}, {:#} and {:?} print?
Show answer
{} prints loading settings. {:#} prints loading settings: permission denied. {:?} prints loading settings, a blank line, Caused by:, and an indented permission denied, followed by a backtrace if RUST_BACKTRACE=1 is set.
Exercise
A teammate defines struct ParseFailure { input: std::rc::Rc<str> } with an Error impl and uses ? on it in an anyhow function. The compiler rejects it. What is wrong, and how do you fix it?
Show answer
Rc<str> is not Send or Sync, so ParseFailure fails the Send + Sync bound required for conversion into anyhow::Error. Replace Rc<str> with Arc<str> or String.