Sub topic 7
Explaining what failed with context
This chapter assumes you can read and write Result-returning functions, use ?, and have anyhow in your Cargo.toml (cargo add anyhow). It also assumes you know that an error can have a source(), as covered in the chapters on the Error trait and #[from]/#[source].
A bare error such as No such file or directory (os error 2) says what the operating system saw. It doesn't say which file, or what your program was doing. anyhow fixes this with the Context trait. It wraps an error in a message you write and keeps the original error as the cause.
The problem context solves
Suppose a program reads a port number from a file. If the file is missing, the ? operator passes the I/O error up unchanged. By the time it reaches main, the message has lost all information about where it came from.
use anyhow::Result;
use std::fs;
fn read_port(path: &str) -> Result<u16> {
let text = fs::read_to_string(path)?;
Ok(text.trim().parse::<u16>()?)
}
fn main() -> Result<()> {
let port = read_port("missing.txt")?;
println!("port {port}");
Ok(())
}Running this prints:
Error: No such file or directory (os error 2)The user can't tell which file is missing. A bad number in the file would be just as vague: invalid digit found in string. Both messages describe a symptom but not the task that failed.
The Context trait
anyhow::Context is a trait implemented for Result<T, E> and for Option<T>. Import it and two methods become available:
| Method | Argument | When the message is built | Column | Column |
|---|---|---|---|---|
| `.context(msg)` | A value that implements `Display` | Immediately, whether or not there is an error | ||
| `.with_context(\ | \ | msg)` | A closure that returns such a value | Only if the result is an error |
Both methods return an anyhow::Result<T>. On success they pass the value through untouched. On failure they build a new error that holds your message and the original error as its source.
Here is the earlier program with context added:
use anyhow::{Context, Result};
use std::fs;
fn read_port(path: &str) -> Result<u16> {
let text = fs::read_to_string(path)
.with_context(|| format!("failed to read {path}"))?;
let port = text
.trim()
.parse::<u16>()
.with_context(|| format!("{path} does not contain a valid port"))?;
Ok(port)
}
fn main() {
if let Err(err) = read_port("missing.txt") {
println!("display: {err}");
println!("alternate: {err:#}");
println!("debug:\n{err:?}");
}
}The output is:
display: failed to read missing.txt
alternate: failed to read missing.txt: No such file or directory (os error 2)
debug:
failed to read missing.txt
Caused by:
No such file or directory (os error 2)Now the error names the file and the task. The original I/O error is still there as the cause.
Three ways to print the same error
An anyhow::Error formats differently depending on the format specifier. This matters because the default is easy to misread.
| Specifier | Output |
|---|---|
| `{}` | Only the outermost message, with no causes |
| `{:#}` | The whole chain on one line, joined with `: ` |
| `{:?}` | The outermost message, then a `Caused by:` list. A backtrace is added when one is captured |
When main returns Err, Rust prints the Debug form, so you get the Caused by: list for free. If you log errors yourself, use {:#} for a single-line log entry. Using plain {} in a log is a common mistake. It hides every cause and leaves you with a message like failed to read missing.txt and no reason.
context versus with_context
The two methods differ only in when the message is built.
use anyhow::{Context, Result};
fn step(n: u32) -> Result<u32> {
if n % 2 == 0 {
Ok(n)
} else {
Err(anyhow::anyhow!("odd number"))
}
}
fn run(n: u32) -> Result<u32> {
// Allocates a String on every call, even when step succeeds.
let a = step(n).context(format!("step failed for {n}"))?;
// Allocates only when step fails.
let b = step(a).with_context(|| format!("second step failed for {a}"))?;
// A string literal needs no allocation, so context is fine.
let c = step(b).context("third step failed")?;
Ok(c)
}
fn main() {
println!("{:#}", run(3).unwrap_err());
}Use these rules:
- For a fixed string literal, use
.context("..."). It costs nothing extra. - For a message built with
format!, use.with_context(|| ...). The formatting runs only on failure, which keeps the success path fast in loops and hot code.
Calling .context(format!(...)) is correct, just wasteful. It is a performance issue, not a bug.
Context on Option
Option has no error, so ? can't turn None into an anyhow::Error by itself. The Context trait fills that gap. None becomes an error whose message is the context you supply.
use anyhow::{Context, Result};
use std::collections::HashMap;
fn lookup<'a>(map: &'a HashMap<String, String>, key: &str) -> Result<&'a String> {
map.get(key)
.with_context(|| format!("missing key: {key}"))
}
fn main() -> Result<()> {
let mut map = HashMap::new();
map.insert("host".to_string(), "localhost".to_string());
println!("host = {}", lookup(&map, "host")?);
println!("port = {}", lookup(&map, "port")?);
Ok(())
}The second lookup fails, and main prints:
host = localhost
Error: missing key: portAn error created from None has no cause, so there is no Caused by: section.
Layering context
Each .context() call wraps the error one more level. In a real program, several functions each add a sentence about their own task. Reading from the outside in, the error then walks you down the call stack.
flowchart LRThe diagram below shows how three layers build one error.
In code, each function adds its own sentence:
use anyhow::{Context, Result};
use std::fs;
fn read_port(path: &str) -> Result<u16> {
let text = fs::read_to_string(path)
.with_context(|| format!("failed to read {path}"))?;
text.trim()
.parse()
.with_context(|| format!("{path} does not contain a valid port"))
}
fn load_config() -> Result<u16> {
read_port("port.txt").context("loading config")
}
fn main() -> Result<()> {
let port = load_config().context("starting server")?;
println!("listening on {port}");
Ok(())
}If port.txt is missing, the program prints:
Error: starting server
Caused by:
0: loading config
1: failed to read port.txt
2: No such file or directory (os error 2)Calling .context() on a value that is already an anyhow::Result is fine. It adds one more layer on top of the existing chain.
Context on top of a thiserror type
Context works on any error type that implements std::error::Error + Send + Sync + 'static. That includes the typed errors you define with thiserror. A library can return a precise enum, and the application adds a sentence about its own task on top.
The original error is not lost. downcast_ref can still reach it through the context layer, so the application can still react to specific variants.
use anyhow::{Context, Result};
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("invalid port")]
InvalidPort(#[from] std::num::ParseIntError),
}
fn parse_port(s: &str) -> Result<u16, ConfigError> {
Ok(s.trim().parse::<u16>()?)
}
fn main() {
let err = parse_port("abc")
.context("reading the server port")
.unwrap_err();
for cause in err.chain() {
println!("- {cause}");
}
println!(
"still a ConfigError: {}",
err.downcast_ref::<ConfigError>().is_some()
);
}The output is:
- reading the server port
- invalid port
- invalid digit found in string
still a ConfigError: trueHere Result<u16, ConfigError> uses anyhow::Result with two type parameters. anyhow::Result<T, E = anyhow::Error> accepts an explicit error type, so one import covers both uses.
Writing good context messages
The compiler can't check the quality of a message, so follow these habits.
- Describe the task, not the failure. The cause already says what went wrong. Write
failed to read port.txt, notfile not found while reading. - Include the values that identify the failure. A path, a key, a user ID, or a URL. These are the details a reader needs to reproduce the problem.
- Don't repeat the cause.
.context("invalid digit found in string")on a parse error adds nothing, and the chain will print it twice. - Keep each message a short phrase. The chain supplies the sentence structure. Use lowercase text with no trailing period, because chains join messages with
:. - Add context at the boundary where information is available. The function that knows the file path should add it. A caller higher up often doesn't have it.
Common mistakes
- Forgetting the import. Without
use anyhow::Context;, the compiler reports that no method namedcontextexists onResult. The method comes from the trait, so the trait must be in scope. - Using
{}when logging. This prints only the outermost layer. Use{:#}or{:?}. - Context on every line. Messages like
"calling parse"and"calling read"describe code instead of intent. Add context where a reader gains information. - Using context when callers need to match. Context creates an opaque wrapper. If a caller must decide what to do based on the kind of failure, return a typed error with a variant for it, as in the
thiserrorchapters. - Calling
.context(format!(...))in a loop. It formats a string on every iteration. Use.with_context.
Exercise
What does println!("{err}") print for an anyhow::Error created by fs::read_to_string("a.txt").with_context(|| "failed to read a.txt"), and which format specifier shows the underlying operating system error on the same line?
Show answer
{err} prints only failed to read a.txt, the outermost context message. The alternate specifier {err:#} prints the whole chain on one line, failed to read a.txt: No such file or directory (os error 2).
Exercise
A function runs let n: i32 = line.parse().context(format!("bad line {line_no}: {line}"))?; inside a loop over a million lines. Rewrite the call so it does no formatting work on lines that parse successfully.
Show answer
Use the lazy form: let n: i32 = line.parse().with_context(|| format!("bad line {line_no}: {line}"))?;. The closure runs only when parse returns Err, so successful lines never build a String.
Exercise
You return ConfigError (a thiserror enum) from a library function, and the application calls .context("loading config") on the result. Can the application still check whether the root error is ConfigError::InvalidPort? How?
Show answer
Yes. Context keeps the original error, so err.downcast_ref::<ConfigError>() on the resulting anyhow::Error returns Some(&ConfigError). The application can then use matches!(e, ConfigError::InvalidPort(_)) or a match on the variant.