Rust's approach to error handling is one of the first hurdles for developers arriving from languages with exceptions, and it remains one of its most powerful features once you internalize it. In my experience building systems services and CLI tooling in Rust over the last four years, the difference between a codebase that is pleasant to maintain and one that fights you often comes down to how you handle the Result type. The community has largely converged on two complementary crates — anyhow and thiserror — and understanding when to reach for each, and how to make them work together, is essential for any intermediate Rust developer moving beyond toy examples. This article shares the patterns I've found most effective for using both crates without sacrificing diagnostics or API clarity.
Why Rust's Result and Error Trait Force a Different Failure Model
Unlike exception-based languages where errors can be thrown from anywhere and caught far up the stack, Rust makes failure a part of a function's signature through Result<T, E>. This was an adjustment for me coming from Python and Go, but it has made my systems code far more predictable. You know exactly which functions can fail and what types of failure to expect, which pays dividends when you are reasoning about resource cleanup and partial state.
Every error type that participates in this system is expected to implement std::error::Error. That trait itself is simple — it requires Display, Debug, and a source() method that lets you walk the chain of causes. The compiler does not force you to define custom error types, but without them you lose the ability to match on specific failure modes. In my early projects I tried to get by with String or Box<dyn Error> everywhere, and debugging became painful because all context was flattened into a single message.
The ? operator is the glue that makes this ergonomic. It early-returns an error while automatically converting it via From. That conversion is what anyhow and thiserror exploit to keep error propagation concise. If you have not yet internalized how ownership interacts with error values moved through ?, I recommend revisiting Rust Ownership and Borrowing: Memory Safety Without Garbage Collection — understanding when an error is moved versus borrowed makes the trait bounds much clearer.
The Cost of Ad-Hoc Error Types
When you define errors ad-hoc with Box<dyn std::error::Error>, you lose exhaustiveness checking. Callers cannot match on a connection timeout versus a malformed payload without downcasting, which is fragile. I've seen production services where every database failure was logged as "unknown error" because the original tokio-postgres error had been boxed and its variant information discarded. Structured errors prevent that.
What Library Consumers Need From Your Errors
A good library error should answer three questions: what happened, why it happened, and what the caller can do about it. The IETF's Problem Details specification RFC 7807 codifies a similar idea for HTTP APIs, separating the error type, title, and underlying cause. In Rust, we achieve the same separation by using typed variants for "what happened" and chaining source for "why it happened."
How anyhow Streamlines Error Handling Inside Applications
I reach for anyhow in every binary, CLI, or integration test suite I write. It provides a single, unifying error type — anyhow::Error — that can wrap any type implementing std::error::Error + Send + Sync + 'static. This is ideal for application code where you don't need to expose specific error variants to downstream consumers; you just need to propagate failures with enough context to diagnose them later.
The core value of anyhow is the context() method. In my experience, a bare ? without context is rarely sufficient in a service. If opening a config file fails, you want to know which path you tried and which operation triggered the failure, not just "No such file or directory (os error 2)".
use anyhow::{Context, Result};
use std::fs;
fn load_config(path: &str) -> Result<Config> {
let content = fs::read_to_string(path)
.with_context(|| format!("failed to read config file at {path}"))?;
let config: Config = toml::from_str(&content)
.context("failed to parse config as TOML")?;
Ok(config)
}
fn main() -> Result<()> {
let cfg = load_config("app.toml")?;
println!("Loaded config for environment: {}", cfg.env);
Ok(())
}
Notice how with_context takes a closure — this avoids allocating the formatted string unless an error actually occurs. In hot paths I've measured a small but meaningful difference when you use context with an eagerly formatted string versus with_context. The resulting error chain, when printed with {:#} or {:?}, will show the full trail: failed to parse config as TOML: failed to read config file at app.toml: No such file or directory.
Adding Backtraces and Downcasting When Diagnostics Demand It
anyhow::Error captures a backtrace on nightly when RUST_BACKTRACE=1 is set, without any extra code. I also rely on downcasting when an application needs to handle a specific case specially — for example, retrying on a transient network error but failing fast on authentication errors. You can call error.downcast_ref::<std::io::Error>() to inspect the root cause, though I try to limit this pattern because it reintroduces coupling to underlying crate internals.
Where anyhow Becomes a Liability in Public APIs
The same flexibility that makes anyhow great for binaries makes it a poor choice for libraries. If your library returns anyhow::Result<T>, callers have no way to programmatically match on your errors without string parsing or downcasting. I made this mistake in an internal crate that parsed financial messages; downstream services had to resort to error.to_string().contains("invalid checksum") to decide whether to nack a message. We refactored to thiserror within a sprint.
Designing Precise, Maintainable Library Errors with thiserror
For any code that will be consumed as a library — whether published to crates.io or shared within a workspace — thiserror is the right default. It is not a runtime error type like anyhow; it is a derive macro that generates implementations of std::error::Error, Display, and From for your own custom enums and structs. The errors remain fully typed and matchable.
In my experience, the most maintainable layout is a single top-level error enum per crate or per module, with variants that wrap both domain-specific failures and underlying causes from dependencies.
use thiserror::Error;
#[derive(Error, Debug)]
pub enum StoreError {
#[error("failed to connect to database at {host}:{port}")]
ConnectionFailed {
host: String,
port: u16,
#[source]
source: std::io::Error,
},
#[error("key '{key}' not found in store")]
NotFound { key: String },
#[error("serialization failed for key '{key}'")]
SerializationFailed {
key: String,
#[source]
source: serde_json::Error,
},
#[error(transparent)]
Io(#[from] std::io::Error),
}
pub fn get_value(store: &Store, key: &str) -> Result<String, StoreError> {
let raw = store.get_raw(key).ok_or_else(|| StoreError::NotFound {
key: key.to_string(),
})?;
Ok(raw)
}
Several things are happening here that are worth unpacking. The #[error("...")] attribute generates the Display impl, so you get human-readable messages without manual boilerplate. Interpolation like {host} and {key} pulls directly from the variant's fields. The #[source] attribute marks which field is the underlying cause, ensuring Error::source() returns the correct chain. And #[from] auto-generates a From<std::io::Error> impl, so the ? operator works seamlessly.
Structuring Variants for Callers, Not Just Logging
I organize variants around the caller's ability to recover. NotFound is something a caller might handle by inserting a default value; ConnectionFailed likely triggers a retry with backoff. If two failures require the same recovery strategy, they probably belong in the same variant. Conversely, avoid a catch-all Other(String) variant — I have found that it inevitably becomes a dumping ground that hides actionable errors. If you need dynamic dispatch for heterogeneous trait objects, the patterns in Trait Objects in Rust: When and How to Use Dynamic Dispatch can help you model errors without sacrificing type safety.
Keeping Error Enums Stable Across Versions
Adding a new variant to a public error enum is a breaking change if callers match exhaustively. In my libraries I add #[non_exhaustive] to the enum so downstream crates are forced to include a wildcard arm. This gives me room to add variants without a major version bump. The Rust reference documentation and general error handling guidance on MDN Web Docs both emphasize stabilizing error contracts early — the same principle applies to Rust crate APIs.
Preserving Diagnostic Context Across Call Stacks Without Boilerplate
The most common complaint I hear about Rust error handling is verbosity, but in practice most of that verbosity comes from failing to add context. A bare ? that propagates a std::io::Error three layers up tells the operator nothing about what the program was trying to do. Both crates solve this, but in different ways.
With thiserror, you add context by creating a new variant that wraps the source. With anyhow, you call .context() at the propagation site. In application code I strongly prefer the latter because it keeps the context adjacent to the operation that failed, rather than defining a new variant for every call site. For example, in an async service that fetches data from multiple microservices, each .await? should explain which service was being contacted:
use anyhow::{Context, Result};
async fn fetch_user_profile(user_id: u64) -> Result<UserProfile> {
let conn = pool.get().await
.context("failed to acquire database connection from pool")?;
let profile = sqlx::query_as::<_, UserProfile>(
"SELECT * FROM users WHERE id = $1"
)
.bind(user_id as i64)
.fetch_one(&conn)
.await
.with_context(|| format!("failed to fetch profile for user_id={user_id}"))?;
Ok(profile)
}
When this fails, the full chain is preserved: the underlying sqlx::Error is still accessible via .source(), but the operator sees "failed to fetch profile for user_id=1234" in logs. If you are building high-concurrency services like this, the error patterns in Async Rust with Tokio: Building High-Performance Network Services complement these techniques well, especially around propagating errors from spawned tasks.
One practice I adopted after a production incident is to always use {:#} (alternate display) when logging anyhow::Error. The default {} prints only the outermost context, while {:#} walks the entire cause chain. Configure your tracing or log framework to use the alternate form, or implement a custom formatter that logs both the error and its sources. Without this, you will lose the root cause in your centralized logging system.
Choosing Between anyhow and thiserror Across Crate Boundaries
The rule of thumb I share with my team is simple: libraries define errors with thiserror, applications handle errors with anyhow. But real workspaces are rarely that clean — you have shared internal crates, binaries that are also imported as libraries in tests, and FFI boundaries where errors cross language lines. Understanding how to translate between the two at those boundaries prevents leaky abstractions.
When application code calls a library that returns a thiserror enum, it can immediately use ? to convert it into anyhow::Error because anyhow::Error implements From<E> for any E: std::error::Error + Send + Sync + 'static. That means you can add application-level context on top of the library's precise error without any extra mapping code.
The reverse direction — converting anyhow::Error back into a typed error — is intentionally difficult and should be avoided. If you find yourself needing to do this, it is a sign that the library boundary is in the wrong place. In my experience, the cleanest solution is to keep anyhow confined to the binary crate and ensure all shared crates expose thiserror types. When you need to call C code via FFI, where errors may come as integer codes or null pointers, map them into your thiserror enum at the unsafe boundary itself — see Rust FFI: Safely Calling C Libraries from Rust Applications for robust patterns on that translation layer.
| Aspect | anyhow | thiserror |
|---|---|---|
| Primary Use Case | Binaries, CLIs, tests, and prototypes | Libraries and shared crates with public APIs |
| Error Type | Single type-erased anyhow::Error that wraps any error |
Custom enums/structs you define with typed variants |
| Caller Experience | Cannot match on variants; must downcast or inspect strings | Exhaustive matching on variants with full compiler support |
| Context Strategy | .context() / .with_context() at call site |
Variant fields with #[source] and explicit wrapping |
| API Stability Impact | No breaking changes to error shape (opaque type) | Adding variants is breaking unless marked #[non_exhaustive] |
| Runtime Overhead | Heap allocation per error; captures backtrace when enabled | No extra allocation beyond your variant fields |
Making Rust Errors Observable in Logs and User-Facing Output
An error type that looks elegant in code is useless if operators cannot diagnose it in production. I've standardized on three practices for observability that work well with both crates. First, always implement Debug — which thiserror does via #[derive(Debug)] — and ensure anyhow errors are logged with their chain. Second, separate user-facing messages from internal diagnostics. For CLI tools, I use eprintln!("Error: {:#}", err) to show the chain to the user while also logging format!("{:?}", err) with a backtrace to a file.
Third, consider structured logging. Instead of formatting errors into a single string, log the top-level message and the source chain as separate fields. With the tracing crate, you can do tracing::error!(error = %err, source = ?err.source(), "operation failed") and then filter on those fields in your observability platform. This is especially important for WebAssembly and browser environments where full backtraces are not available — the error chain itself becomes your primary debugging tool, much as it does when building high-performance frontends discussed in Rust and WebAssembly: Building High-Performance Web Applications.
Finally, test your errors. I write unit tests that assert the Display output of each thiserror variant and that the source() chain is intact. For anyhow paths, I test that the context messages are present using err.to_string().contains("expected substring") and that downcasting still works after wrapping. It takes only a few minutes to add these tests and they catch regressions when someone refactors an error message or removes a #[source] attribute by accident.
Effective error handling in Rust is not about picking one crate over the other — it is about using each where it reduces friction. Use thiserror to define the contract your code offers to its callers, and use anyhow to enrich failures with the context you need to operate the system. In my experience, teams that adopt this split early spend far less time chasing vague error messages and far more time fixing the underlying issues.
Frequently Asked Questions
Can I use anyhow and thiserror in the same crate?
Yes, and you should when the crate contains both library and binary targets. Define your public error types with thiserror in lib.rs so external consumers get typed errors, and use anyhow::Result inside main.rs or bin/ binaries to add context when calling those library functions. The two interoperate cleanly because anyhow::Error can wrap any thiserror type via its blanket From implementation.
Does thiserror have any runtime performance cost?
No. thiserror is a procedural macro that generates standard Rust trait implementations at compile time. It produces the same code you would write by hand — impls for Display, Error, and From — so there is no extra allocation, dynamic dispatch, or runtime overhead beyond the fields you define in your enum variants.
How do I avoid losing the source chain when converting errors?
Always annotate the underlying cause with #[source] in thiserror variants and use .context() rather than creating a new error from a string in anyhow code. Avoid patterns like Err(anyhow!("failed: {}", err)) which flatten the chain into a string; use Err(err).context("failed") instead so Error::source() remains walkable and can be inspected in logs with {:#}.
Should I expose anyhow::Error in a library's public function signature?
Generally no. Exposing anyhow::Error in a public API forces all consumers to depend on anyhow and prevents them from matching on specific failure modes. Reserve anyhow::Error for applications and internal helper functions. For public library functions, return Result<T, YourError> where YourError is a thiserror enum that callers can match exhaustively.