Skip to content
rusthacks.dev
Rust

Anyhow vs Thiserror and Which One to Use in Your Crate

Use thiserror when callers need to match on what went wrong and anyhow when they only need to read it. Here is the rule, the code for each, and how to mix them.

8 min read
Summarize in AI
Flat illustration for the post “Anyhow vs Thiserror and Which One to Use in Your Crate”, composed around errors.

Two crates dominate Rust error handling, and they are not rivals. thiserror helps you write a precise error type that callers can match on. anyhow gives you a single catch-all error type that carries a message and a chain of causes, for code where nobody will match. The question "which one in my crate" has a short answer, and the short answer has an exception. This post shows both crates on the same small program, what each produces when it fails, how they work together, the size and speed difference, and the rule to apply per crate. Everything compiled on Rust 1.99, edition 2024, with thiserror 2 and anyhow 1.

The decision in one sentence

A library returns its own error type (usually with thiserror); an application returns anyhow::Result. The difference is who consumes the error. A library's caller may want to retry on a timeout but give up on a permission failure, and can only do that if the error is an enum or a struct with fields to inspect. An application's main only wants to print what went wrong, with context, and exit; it never matches on a variant, so the precision costs boilerplate and buys nothing.

The same function with thiserror

Take a function that loads a service's configuration from text. With thiserror the error is a plain enum. The derive writes Display from the #[error(...)] strings, implements std::error::Error, and generates From impls for fields marked #[from]:

rust
use std::num::ParseIntError;
use thiserror::Error;

#[derive(Debug, Error)]
enum ConfigError {
    #[error("missing key `{0}`")]
    Missing(&'static str),

    #[error("`{key}` must be a whole number")]
    BadNumber {
        key: &'static str,
        #[source]
        source: ParseIntError,
    },

    #[error("port {0} is reserved")]
    ReservedPort(u16),
}

fn get<'a>(pairs: &'a [(&str, &str)], key: &'static str) -> Result<&'a str, ConfigError> {
    pairs.iter().find(|(k, _)| *k == key).map(|(_, v)| *v).ok_or(ConfigError::Missing(key))
}

fn port(pairs: &[(&str, &str)]) -> Result<u16, ConfigError> {
    let p: u16 = get(pairs, "port")?
        .parse()
        .map_err(|source| ConfigError::BadNumber { key: "port", source })?;
    if p < 1024 {
        return Err(ConfigError::ReservedPort(p));
    }
    Ok(p)
}

fn main() {
    for case in [vec![("port", "8080")], vec![], vec![("port", "http")], vec![("port", "80")]] {
        match port(&case) {
            Ok(p) => println!("ok {p}"),
            Err(ConfigError::ReservedPort(p)) => println!("retry with a port above 1023, not {p}"),
            Err(e) => println!("error: {e}"),
        }
    }
}
Text
ok 8080
error: missing key `port`
error: `port` must be a whole number
retry with a port above 1023, not 80

The caller got a decision it could not have made with a string: for a reserved port, try another number; for anything else, report. That is the entire argument for a typed error. Each variant is a part of the library's public API, so adding a variant is a semver event; mark the enum #[non_exhaustive] to make additions non-breaking. The hand-written equivalent of this derive is in Result explained, and it is about forty lines longer.

The same program with anyhow

In the application that calls this library, an error is a thing to report. anyhow::Error wraps any error that implements std::error::Error + Send + Sync + 'static, so ? converts from anything, and .context("...") adds a layer of explanation:

rust
use anyhow::{bail, Context, Result};

fn parse_workers(raw: &str) -> Result<usize> {
    let n: usize = raw.trim().parse().with_context(|| format!("invalid worker count {raw:?}"))?;
    if n == 0 {
        bail!("worker count must be at least 1");
    }
    Ok(n)
}

fn load(settings: &str) -> Result<usize> {
    let line = settings.lines().find(|l| l.starts_with("workers=")).context("settings has no `workers=` line")?;
    parse_workers(&line["workers=".len()..]).context("while loading settings")
}

fn main() -> Result<()> {
    println!("{}", load("name=x\nworkers=8")?);

    for text in ["name=x", "workers=many", "workers=0"] {
        match load(text) {
            Ok(n) => println!("{n}"),
            Err(e) => println!("{e:#}"),
        }
    }

    let n = load("workers=lots")?;
    println!("unreachable {n}");
    Ok(())
}
Text
8
settings has no `workers=` line
while loading settings: invalid worker count "many": invalid digit found in string
while loading settings: worker count must be at least 1
Error: while loading settings

Caused by:
    0: invalid worker count "lots"
    1: invalid digit found in string

Three details to notice. {e:#} prints the whole chain on one line, outermost context first. A bare {e} would print only the outermost message ("while loading settings"). The final ? in main shows the default report format: the top message, then a "Caused by:" list, which is already what a user needs. And bail! and .context() removed the need for an enum entirely: none of these failures is something the program will branch on.

Using both: the usual shape of a real project

The two crates compose, and most workspaces use both. Library crates inside the workspace define typed errors with thiserror; the binary calls them with anyhow and gets conversions for free, because a thiserror type implements std::error::Error:

rust
use anyhow::{Context, Result};
use thiserror::Error;

mod storage {
    use super::*;

    #[derive(Debug, Error)]
    pub enum StorageError {
        #[error("record {0} not found")]
        NotFound(u32),
        #[error("storage is read-only")]
        ReadOnly,
    }

    pub fn fetch(id: u32) -> Result<String, StorageError> {
        match id {
            1 => Ok("alice".into()),
            99 => Err(StorageError::ReadOnly),
            _ => Err(StorageError::NotFound(id)),
        }
    }
}

fn profile(id: u32) -> Result<String> {
    let name = storage::fetch(id).with_context(|| format!("building profile for user {id}"))?;
    Ok(format!("profile of {name}"))
}

fn main() {
    for id in [1, 7, 99] {
        match profile(id) {
            Ok(p) => println!("{p}"),
            Err(e) => {
                if let Some(storage::StorageError::NotFound(_)) = e.downcast_ref::<storage::StorageError>() {
                    println!("{e:#} (a 404, not a crash)");
                } else {
                    println!("{e:#}");
                }
            }
        }
    }
}
Text
profile of alice
building profile for user 7: record 7 not found (a 404, not a crash)
building profile for user 99: storage is read-only

The escape hatch is downcast_ref: when the application does need to branch on one specific library error, it can ask the anyhow::Error for the typed value inside. If you find yourself doing that in many places, the application has become a library in disguise, and a typed error at that layer is worth the boilerplate.

What each one costs

An anyhow::Error is a single pointer to a heap allocation holding the error, its vtable and (when enabled) a backtrace. A thiserror enum is as big as its largest variant, stored inline. That changes the size of every Result that carries it:

rust
use std::mem::size_of;
use thiserror::Error;

#[derive(Debug, Error)]
enum Small {
    #[error("a")]
    A,
    #[error("b {0}")]
    B(u32),
}

#[derive(Debug, Error)]
enum Large {
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
    #[error("path {path}: {reason}")]
    Path { path: String, reason: String },
}

fn main() {
    println!("Result<u64, anyhow::Error>  {} bytes", size_of::<Result<u64, anyhow::Error>>());
    println!("Result<u64, Small>          {} bytes", size_of::<Result<u64, Small>>());
    println!("Result<u64, Large>          {} bytes", size_of::<Result<u64, Large>>());
    println!("Result<u64, Box<dyn Error>> {} bytes", size_of::<Result<u64, Box<dyn std::error::Error>>>());
    println!("anyhow::Error             {} bytes", size_of::<anyhow::Error>());
}
Text
Result<u64, anyhow::Error>  16 bytes
Result<u64, Small>          16 bytes
Result<u64, Large>          48 bytes
Result<u64, Box<dyn Error>> 16 bytes
anyhow::Error             8 bytes

The anyhow result is 16 bytes, small enough to return in registers; the enum with a String pair in a variant is larger. Clippy warns about Result with a large error through result_large_err (the default limit is 128 bytes) because a big Err makes the happy path copy it around too. The usual fix is to box the large variant payload or the whole error. Allocation costs one malloc when an anyhow error is created, which happens only on the error path and is not measurable next to the I/O that failed. Only code that fails in a tight loop (parsing millions of lines of which many are invalid) should avoid an allocation per failure, and for that a plain enum with Copy fields is the right tool.

Migrating between them later

The choice is cheap to reverse, which is one reason not to agonise over it. Moving from anyhow to a typed error is a mechanical job: introduce the enum, change the function signature, and the compiler lists every ? that now needs a From impl or a map_err. Callers that used downcast_ref start matching on variants instead. Going the other way is even simpler: change the return type to anyhow::Result and every ? keeps working, because anything implementing std::error::Error converts. A good trigger for the first move is the second time you write downcast_ref for the same error. A good trigger for the second is a typed error with eight variants, none of which any caller ever inspects.

One habit pays off in both worlds: write the message for the person who will read the log at three in the morning. "failed to open file" says nothing. "while loading settings: invalid worker count "many"" names the operation, the input and the reason, which is what .context() and #[error("...")] are for. Include the identifier that distinguishes this failure from the thousand others (the path, the user id, the key) and leave out anything the reader could not act on.

Choosing for your crate

You are writingUseWhy
A library on crates.iothiserror enum, #[non_exhaustive]Callers must be able to match
A binary or CLIanyhowOnly reports; context chains read well
An internal workspace library used by one binaryEither; start with thiserror if a caller will branchPromote later at no cost
A web handler boundaryA typed error that implements the framework's response traitEach variant maps to an HTTP status, see axum error handling
A testanyhow::Result in the test functionUse ? without ceremony
Code that fails in a hot loopA small Copy enumNo allocation

Where neither is the answer

If the crate has one failure mode, a unit struct with a Display impl is enough and needs no dependency. If you need to report several independent failures at once (validating a form), build an error that holds a vector of them rather than stopping at the first. If you are in an embedded or no_std context, neither crate's default features apply, and thiserror 2 supports no_std while anyhow needs alloc. And the heavyweight alternatives (snafu, eyre and miette) exist for richer reports; the broader picture of how errors cross layers is in error boundaries.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.