anyhow
Flexible app errors.
anyhow is a free Learn Rust Coding lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Flexible Application Errors
In application code you often just want errors to bubble up with context, without defining a typed enum for each. The anyhow crate provides one easy error type for exactly that.
Adding anyhow
Add it as a dependency. It pairs well with thiserror: thiserror for libraries, anyhow for binaries.
[dependencies]
anyhow = "1.0"The anyhow::Result Alias
anyhow::Result<T> is shorthand for Result<T, anyhow::Error>. The Error type can hold any error that implements std::error::Error.
use anyhow::Result;
fn load() -> Result<String> {
let text = std::fs::read_to_string("config.txt")?;
Ok(text)
}Automatic Conversion
The ? operator converts any standard error into anyhow::Error automatically, so you can mix error types freely.
use anyhow::Result;
fn parse_file(path: &str) -> Result<i32> {
let text = std::fs::read_to_string(path)?; // io error
let n: i32 = text.trim().parse()?; // parse error
Ok(n)
}Adding Context
The .context() method attaches a human-friendly message to an error, building a readable chain when things fail.
use anyhow::{Context, Result};
fn read_config(path: &str) -> Result<String> {
let text = std::fs::read_to_string(path)
.context("failed to read config file")?;
Ok(text)
}Lazy Context
Use with_context when building the message is expensive or needs runtime data; the closure runs only on error.
use anyhow::{Context, Result};
fn open(path: &str) -> Result<String> {
std::fs::read_to_string(path)
.with_context(|| format!("could not open {path}"))
}Creating Ad-hoc Errors
The anyhow! macro builds an error from a message, and bail! returns early with one.
use anyhow::{anyhow, bail, Result};
fn check(age: i32) -> Result<()> {
if age < 0 {
bail!("age cannot be negative");
}
if age > 150 {
return Err(anyhow!("age {age} is implausible"));
}
Ok(())
}Using ensure!
ensure! is like assert! but returns an error instead of panicking.
use anyhow::{ensure, Result};
fn divide(a: i32, b: i32) -> Result<i32> {
ensure!(b != 0, "division by zero");
Ok(a / b)
}anyhow in main
Return anyhow::Result<()> from main to get nicely formatted error chains printed on failure.
use anyhow::Result;
fn main() -> Result<()> {
let text = std::fs::read_to_string("data.txt")?;
println!("{text}");
Ok(())
}Inspecting the Cause
Even though anyhow::Error is opaque, you can still inspect it. downcast_ref recovers a concrete error type when you need to branch on it.
use anyhow::Result;
fn report(err: anyhow::Error) {
if let Some(io) = err.downcast_ref::<std::io::Error>() {
println!("io error: {io}");
} else {
println!("other error: {err}");
}
}thiserror vs anyhow
Rule of thumb:
- thiserror — libraries, typed errors callers match on
- anyhow — applications, just propagate with context
You can convert a thiserror error into anyhow with ? seamlessly.
Quick Check
Which anyhow method attaches a descriptive message to an error as it propagates?
Recap
You learned the anyhow crate:
anyhow::Result<T>uses one flexible error type?converts any standard error automatically.context()/with_context()add readable messagesanyhow!,bail!, andensure!create errors- Best for application (binary) code
Frequently asked questions
Is the “anyhow” lesson free?
Yes — the full text of “anyhow” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “anyhow”?
Flexible app errors. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “anyhow” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.