
Recall first from Custom errors and thiserror
- An error enum gives callers named variants and typed fields.
- A From implementation lets the question-mark operator convert an underlying error into the function's error type.
- A thiserror field marked #[from] also serves as the source.
Report failures with anyhow
4 min readYou built typed errors with thiserror. This lesson answers when to switch to anyhow and how to choose between the two crates.
A configuration reader on an embedded Linux device can fail before it has any settings to work with. Linux can reject an attempt to open a missing file or deny access to it. A read can also fail after the file opens. Those causes matter, but an operator seeing the error also needs to know which configuration file the command tried to load. That path is available to the code making the request. open(2), read(2)
anyhow::Result<T> is an alias for Result<T, anyhow::Error> when you supply only T. A function with that return type can use ? on operations that return different compatible errors. For example, it can propagate a filesystem error from std::fs::read_to_string and a parse error from str::parse::<u64>. Both become anyhow::Error, and each underlying error retains its concrete type. The signature tells the caller what success contains. It leaves the set of possible error types open.
Import anyhow::Context to use .context(...) and .with_context(...) on these results. Both methods pass the successful value through. On failure they attach a description and retain the error that caused the operation to fail.
use anyhow::{Context, Result};
use std::{fs, path::Path};
fn load_interval(path: &Path) -> Result<u64> {
let text = fs::read_to_string(path)
.with_context(|| format!("read interval from {}", path.display()))?;
let millis = text.trim().parse::<u64>()
.context("parse interval as a whole number of milliseconds")?;
Ok(millis)
}
Use .context("...") for a description you already have, such as a string literal. Rust evaluates the argument before calling the method, so .context(format!(...)) formats a string on success as well as on failure. .with_context(|| format!(...)) calls the closure only when the result is an error. That makes it a good fit when the description needs a path or another value from the current operation.
Run with a file containing abc and with a missing path, the function above gives (real output of a main that calls it, printed by returning the error from main):
Error: parse interval as a whole number of milliseconds
Caused by:
invalid digit found in string
Error: read interval from /tmp/zmissing
Caused by:
No such file or directory (os error 2)
Write context that answers a question the underlying error leaves open. The filesystem error can explain why the read failed. The context identifies the file and its purpose. The parse error can explain why the conversion failed. The context tells the operator what value the command expected. In this example, a failed read returns immediately, and the parse context appears only if the read succeeds and parsing fails. A caller can also attach context to load_interval(...) itself to explain why it requested the interval.
A function can also detect a failure directly. anyhow!("interval must be greater than zero") constructs an anyhow::Error value. You can return it with Err(...) or use it in a closure such as ok_or_else. bail!("interval must be greater than zero") returns an error immediately from the enclosing function. In a function returning anyhow::Result, it serves the same purpose as return Err(anyhow!("interval must be greater than zero")). Both macros support formatted messages. Use a fresh message when your code detects a condition such as a disallowed zero. When a called operation already supplies an error, attach context to retain its cause.
Choose an error type at the library and binary boundary
3 min readStart with the decision the caller needs to make. A Linux daemon that uses an interval-reading library might allow a built-in default when an optional settings file is missing. A file that exists but contains an invalid interval needs a different response. The daemon can make that distinction by matching on the library's error enum and checking the I/O error kind where relevant. With thiserror, the enum is an ordinary Rust type and the derive supplies its standard error implementation. Its variants and fields give callers a documented way to make decisions in code.
A binary often has a different job. It receives arguments, calls a library, writes a result, and reports failures to the person or service that invoked it. If the response to each failure is to report what happened and exit, anyhow::Result lets these operations share a return type and keep their causes. Use these as defaults for reusable library APIs and command-level code. Application code can also use a typed error wherever a decision depends on the failure case. For a public enum, consider which variants callers are meant to depend on, since changes to that enum can affect their matches.
Suppose the library already exposes load_interval(&Path) -> Result<u64, IntervalError>. Its Read and Parse variants preserve their respective source errors, and Zero represents a parsed value the library rejects. A command can use that library with a small amount of reporting code. In the example below, interval_tool is the library name.
use anyhow::{anyhow, Context, Result};
use std::{
env,
io::{self, Write},
path::PathBuf,
};
fn main() -> Result<()> {
let path = env::args_os().nth(1).map(PathBuf::from)
.ok_or_else(|| anyhow!("expected a configuration file path"))
.context("read the command-line configuration argument")?;
let millis = interval_tool::load_interval(&path)
.with_context(|| format!("load interval from {}", path.display()))?;
writeln!(io::stdout().lock(), "{millis}")
.context("write the interval to standard output")?;
Ok(())
}
args_os lets the binary accept Linux paths that contain bytes outside UTF-8. The lookup returns an Option, so ok_or_else supplies an error for an absent argument. The library call adds the path only on failure. The write is fallible too. Handling its result lets the command report an output failure, such as a closed pipe, through the same return type. When main returns an error, Rust reports it to standard error and exits unsuccessfully. The context tells the operator what the command was doing, and the underlying error supplies the cause. These are real runs of this binary against the library above, built with anyhow 1.0.105, thiserror 2.0.21 and rustc 1.100.1 (the file contents were 25, 0, abc, and a path that does not exist). The exit status is 1 for every failure:
$ interval_tool /tmp/z25
25
$ interval_tool /tmp/z0
Error: load interval from /tmp/z0
Caused by:
interval must be greater than zero
$ interval_tool /tmp/zabc
Error: load interval from /tmp/zabc
Caused by:
0: interval must be an unsigned integer
1: invalid digit found in string
$ interval_tool /tmp/zmissing
Error: load interval from /tmp/zmissing
Caused by:
0: cannot read interval file /tmp/zmissing
1: No such file or directory (os error 2)
$ interval_tool
Error: read the command-line configuration argument
Caused by:
expected a configuration file path
In a panicking version of this command, unwrap() might be used to get the argument, read the file, and parse the number. During the refactor, move reading, parsing, and the positive-interval rule into the library. Map read and parse failures to their typed variants, preserving their sources, and return IntervalError::Zero for zero. Keep argument handling and output in the binary. Add context at each fallible command step, using .context() for literal descriptions and .with_context() when you need to format a path. A valid file should still produce the same interval after the refactor. A missing file, invalid number, or zero should now return through the normal error path.
Recover a typed error when the binary needs it
2 min readSometimes a command that normally reports and exits has a special response to one failure. It might show a configuration hint when the interval is zero. anyhow::Error::downcast_ref::<IntervalError>() attempts to borrow the stored error as that concrete type. It returns Some(&IntervalError) on a match and None when the requested type is absent. Context attached through anyhow preserves this ability, so the command can inspect the error after adding the path.
use anyhow::{Context, Result};
use interval_tool::{load_interval, IntervalError};
use std::path::Path;
fn interval_hint(path: &Path) -> Result<u64> {
load_interval(path)
.with_context(|| format!("load interval from {}", path.display()))
.map_err(|error| {
if let Some(IntervalError::Zero) = error.downcast_ref::<IntervalError>() {
eprintln!("Set the interval to a positive number of milliseconds.");
}
error
})
}
Here map_err runs only on failure. The borrow ends before the closure returns the original anyhow::Error, so the caller still receives the full report. Success passes through unchanged. A different IntervalError variant still downcasts successfully, but the Zero pattern does not match it. If the command needs the typed value by ownership, downcast::<IntervalError>() consumes the anyhow::Error and returns either the typed value or the original error on a failed match.
Downcasting checks types rather than comparing wording. Request IntervalError when the library returned that enum. If a read failed, match its Read variant and inspect the source it stores to decide whether the file was missing. An I/O error stored as the source of a library variant is a different case from an I/O error directly wrapped by anyhow. Downcasting to the enum gives you the library-level information needed to inspect that source explicitly.
Consider where you would put the default for a missing optional file. If each caller decides whether a file is optional, keep the error typed at that decision and let each caller choose its response. If the binary owns the decision and already has an anyhow report, a downcast can handle that case while preserving diagnostics for other failures. In the next lesson, Modules, paths, crates, and workspaces, you will see how Rust organizes and names the library code and the binary that calls it.
Key takeaways
- anyhow::Result<T> uses anyhow::Error as its default error type.
- Context adds a description while preserving the original error.
- A public error enum gives callers variants they can match when deciding how to recover.
- A binary can use anyhow to report errors returned by a library that uses thiserror.
Reflect
- Explain to a colleague, in two sentences: return different error types through anyhow::Result.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Crate docsanyhow 1.0 documentation
- Crate docsthiserror 2.0 documentation
- Rust docsThe Rust Book: To panic! or not to panic!
- Man pageopen(2): opening files and reporting errors
- Man pageread(2): reading files and reporting errors
Official documentation first. Links checked when the lesson was published.