Sub topic 7
Explaining what failed with context
This chapter assumes you know Result, the ? operator, and the basics of anyhow::Result from the previous chapter. You should also be able to add a crate with Cargo.
The problem: bare errors say too little
A plain ? on an I/O error passes the original message up unchanged. If a program reads several files, the user may see only this:
Error: No such file or directory (os error 2)That message names the operating system problem. It does not say which file, or what the program was doing. Context fixes this by wrapping the original error in a message that describes the failed step.
The Context trait
anyhow provides the Context trait. It adds two methods to Result and Option:
.context(msg)takes a message that is built right away..with_context(|| msg)takes a closure that builds the message only if an error occurs.
Both return an anyhow::Result. The original error becomes the source of the new one, so nothing is lost. Add the crate first:
cargo add anyhowHere is a function that adds context at each fallible step:
use anyhow::{Context, Result};
use std::fs;
fn load_port(path: &str) -> Result<u16> {
let text = fs::read_to_string(path)
.with_context(|| format!("failed to read {path}"))?;
let port: u16 = text
.trim()
.parse()
.context("port is not a valid u16")?;
Ok(port)
}
fn main() -> Result<()> {
let port = load_port("port.txt")?;
println!("listening on {port}");
Ok(())
}If port.txt does not exist, Rust prints the error returned from main using its Debug form. anyhow makes that form show the whole chain:
Error: failed to read port.txt
Caused by:
No such file or directory (os error 2)The outer message says what the program was doing. The inner message says why it failed.
Choosing between context and with_context
Use .context("fixed text") when the message is a string literal. It costs nothing extra.
Use .with_context(|| ...) when the message needs format!. A format! call allocates a String. If you pass it to .context(...), that allocation happens on every call, including successful ones. The closure form runs only on failure.
use anyhow::{Context, Result};
fn first_line(path: &str) -> Result<String> {
let text = std::fs::read_to_string(path)
.with_context(|| format!("failed to read {path}"))?;
text.lines()
.next()
.map(str::to_string)
.context("file is empty")
}The last line shows Context on an Option. A None becomes an error carrying the message you give. This is a compact way to turn a missing value into a reported failure.
How context layers build up
Each call to .context adds one layer. When several functions each add context, the final error reads from the outermost step to the innermost cause.
use anyhow::{Context, Result};
fn read_port(path: &str) -> Result<u16> {
let text = std::fs::read_to_string(path)
.with_context(|| format!("failed to read {path}"))?;
text.trim().parse().context("port is not a valid u16")
}
fn start_server(path: &str) -> Result<()> {
let port = read_port(path).context("could not start server")?;
println!("listening on {port}");
Ok(())
}
fn main() -> Result<()> {
start_server("port.txt")
}A file containing abc produces this output:
Error: could not start server
Caused by:
0: port is not a valid u16
1: invalid digit found in stringCommon mistakes
- Repeating the cause in the message. Write "failed to read config", not "failed to read config: No such file". The source is printed for you.
- Using
{}to print the error.println!("{err}")shows only the outermost message. Use{err:#}to join the chain on one line, or{err:?}for the multi-line report. - Adding context that says nothing. "error" or "failed" adds no information. Name the operation and the input.
- Expecting
.contexton a custom error to keep its type. The result is ananyhow::Error. You can still recover the original type with downcasting, covered in a later chapter.
Exercise
A function calls std::fs::read_to_string(path).context(format!("reading {path}"))? in a loop that usually succeeds. What is wrong, and how do you fix it?
Show answer
format! runs and allocates a String on every iteration, even when no error occurs. Replace .context(format!(...)) with .with_context(|| format!("reading {path}")) so the message is built only on failure.
Exercise
A caller prints an error with println!("{err}") and sees only "could not start server". Which format specifier shows the full cause chain on one line?
Show answer
{err:#}. It prints the outer message followed by each cause, separated by colons. {err:?} also shows the chain, in a multi-line report.