What is anyhow?
anyhow is a Rust crate by David Tolnay(2019) that gives application code
one error type —
anyhow::Error. You return
anyhow::Result<T> and use ? to bubble
errors up to main without writing a custom error
enum for every failure.
Why anyhow: Different steps can fail with different error types
(reqwest::Error, std::io::Error, …). anyhow
converts them all into one type.
anyhow::Context::context(...) adds a short message so you
know where it failed.
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let response = anyhow::Context::context(
reqwest::get("https://example.com").await,
"HTTP request failed",
)?;
let body = anyhow::Context::context(
response.text().await,
"reading response body failed",
)?;
println!("{body}");
Ok(())
}
If something fails, you see a chain like:
reading response body failed → HTTP request failed → ...
If we don't use anyhow, what do we lag behind on?
Custom error enums everywhere — you must define
enum AppError and add From for every library
error type yourself.
No easy context chain — without .context(), errors
only say “connection reset” with no hint that it happened during “fetch
user config”.
Box<dyn Error> boilerplate — works for
propagation, but no context, downcast, or backtrace helpers out of the
box.
Mixed error types in main — hard to combine I/O,
HTTP, JSON, and DB errors in one return type without anyhow or a large
hand-written enum.
Slower debugging — more time tracing failures because messages
don't stack up step by step.
Scopes for anyhow
| Where | Use anyhow? |
|---|---|
main, CLI, server binary |
Yes |
| Library public API (other crates call you) | No — use thiserror |
| Private helpers inside your app | Yes |
Compare with other crates
| Crate | Role |
|---|---|
| anyhow | One error type at the app top — propagate with ? |
| thiserror |
Typed errors in libraries — callers can match variants
|
| eyre |
Same niche as anyhow; often paired with color-eyre for
pretty reports
|
| tracing | Logging and spans — complements anyhow; anyhow carries the error, tracing logs events |