skip to content

Context and Backtraces

An error that reaches the top needs its cause chain and enough context to act on. Interviewers ask how to add context without losing the source and when to capture a backtrace.

on this pageshow

questions

5

In a Rust tool using anyhow, how do you make an io::Error from fs::read_to_string say which manifest file failed?

level: juniorimportance: must knowfreq 60%

answer

  1. an extension trait to import
  2. a method on the Result
  3. a closure for formatted text
  4. the io::Error stays underneath

basics

~10 s

Import anyhow::Context and call .with_context(|| format!("failed to load manifest {}", path.display())) on the Result. The Err becomes an anyhow::Error whose message names the file, with the original io::Error kept as its source.

solid answer

~40 s

A `std::io::Error` from `fs::read_to_string` says `No such file or directory (os error 2)` but does not include the path. With anyhow, bring the extension trait into scope with `use anyhow::Context;` and write `fs::read_to_string(path).with_context(|| format!("failed to load manifest {}", path.display()))?`. That turns `Result<String, io::Error>` into `anyhow::Result<String>`: the new message becomes the error's `Display`, and the `io::Error` is kept underneath as its source, so `{:#}` prints both and `downcast_ref::<io::Error>()` still finds it. Use `.context("fixed text")` when the message is a constant; `with_context` takes a closure, so the `format!` runs only on the error path. Both methods also work on `Option`, turning `None` into an error.

code

rust · 17 lines
rust
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;

fn load_manifest(path: &Path) -> Result<String> {
    let text = fs::read_to_string(path)
        .with_context(|| format!("failed to load manifest {}", path.display()))?;
    Ok(text)
}

fn main() {
    let err = load_manifest(Path::new("deploy/prod.toml")).unwrap_err();
    println!("{err}");
    println!("{err:#}");
    let io = err.downcast_ref::<std::io::Error>().unwrap();
    println!("io kind: {:?}", io.kind());
}

go deeper

for a junior

Recall the import, use anyhow::Context, and the two methods: context for fixed text, with_context with a closure when you format a path or id into the message.

for a middle

Explain that the message becomes the outer layer while the io::Error is stored as its source, and that context evaluates its argument eagerly while with_context defers it to the error path.

for a senior

Show where context belongs: at the layer that still knows the path, not at the top. Mention that downcast_ref still reaches the io::Error, so callers can branch on its kind.

for a principal

Frame context as a convention a codebase enforces: every fallible I/O call carries the resource it touched, so operators never see a bare os error 2 in production logs.

## Why the bare error is not enough When `std::fs::read_to_string` fails, it returns a `std::io::Error`. That type carries an **error kind** (`NotFound`, `PermissionDenied`, ...) and, for operating-system failures, the OS error code. It does **not** carry the path you passed in. Printed, it reads `No such file or directory (os error 2)`. In a deployment tool that loads a dozen manifest files, that message reaches the operator with no hint of *which* file was missing. Rust does not use exceptions for recoverable errors, and an `Err` carries no automatic record of the calls it passed through. Whatever a caller needs to know has to be put into the error value on its way up. That is what **context** means here: a human-readable layer, added at the point where the code still knows what it was trying to do. ## Adding context with the anyhow `Context` trait The `anyhow` crate provides an extension trait, `anyhow::Context`, implemented for `Result<T, E>` (where `E` is a std error that is `Send + Sync + 'static`, or already an `anyhow::Error`) and for `Option<T>`. It adds two methods: - **`context(msg)`** takes any value that implements `Display + Send + Sync + 'static` and wraps the error with it. - **`with_context(|| msg)`** takes a closure (`FnOnce() -> C`) and calls it only if the value is an `Err` or `None`. ```rust use anyhow::{Context, Result}; fn load_manifest(path: &std::path::Path) -> Result<String> { std::fs::read_to_string(path) .with_context(|| format!("failed to load manifest {}", path.display())) } ``` Three things happen in that call: 1. The `Result<String, io::Error>` becomes `Result<String, anyhow::Error>`, which is what `anyhow::Result<String>` means. 2. The new error's `Display` is your message, `failed to load manifest deploy/prod.toml`. 3. The original `io::Error` is stored **underneath** as the wrapped error's source, not discarded. Because it is a trait method, the trait must be in scope. Forgetting `use anyhow::Context;` gives error[E0599], "no method named `with_context` found for enum `Result<T, E>` in the current scope", and rustc's help line suggests the import. ## `context` vs `with_context` | | `context(msg)` | `with_context(closure)` | |---|---|---| | Argument | a value that is `Display + Send + Sync + 'static` | a closure returning such a value | | When the message is built | before the call, on every path, including `Ok` | only when the result is `Err` or `None` | | Best for | a fixed `&'static str` | `format!` with a path, id or other runtime data | The difference is ordinary Rust evaluation: an argument expression is evaluated before the method runs. `x.context(format!("loading {path}"))` allocates and formats a `String` even when the read succeeded; `with_context` defers that work to the failure path. ## What the wrapped error keeps - **The cause chain.** `err.chain()` yields your message, then the `io::Error`. Printing with `{:#}` gives `failed to load manifest deploy/prod.toml: No such file or directory (os error 2)`. - **Downcasting.** `err.downcast_ref::<std::io::Error>()` still returns `Some`, so code can check `kind() == NotFound` and decide what to do. anyhow documents that for an error with context, a downcast matches either the context type or the error it was attached to. - **A backtrace**, if backtraces are enabled through the environment; how that works is a separate topic. ## Mistakes that show up in review - Passing a closure to `context`: `.context(|| format!(...))` fails with `error[E0277]`, because a closure does not implement `Display`. Closures go to `with_context`. - Passing a borrow of a local: `.context(&msg)` where `msg` is a local `String` fails with error[E0597], "`msg` does not live long enough", because the message must be `'static`. Pass the `String` by value. - Re-typing the io error into the message string instead of wrapping it, which makes the source unreachable. - Adding context only at the top level, where the path is no longer known. Add it where the knowledge is. ## On `Option` The same trait turns `None` into an error: `config.get("host").context("no deploy host configured")?`. There is no source in that case; the message is the whole error, a chain of one. ## A short checklist for review 1. Every fallible file, network or parse call that can fail for an operator-visible reason carries the resource it touched: the path, the host, the record id. 2. Constant messages use `context`; messages built with `format!` use `with_context`. 3. The message describes what was being attempted (`failed to load manifest ...`) and does not repeat the cause, because the cause is printed separately when the chain is rendered. 4. Callers that branch on the cause use `downcast_ref` on the `anyhow::Error` rather than matching on the message text.

  • Why does `.context(|| format!("loading {path}"))` not compile?
    `context` takes the message itself, which must implement `Display + Send + Sync + 'static`. A closure does not implement `Display`, so rustc reports `error[E0277]` saying the closure doesn't implement `std::fmt::Display` and suggests calling it. A closure belongs in `with_context`, which accepts any `FnOnce() -> C` and calls it only on failure.
  • Can you pass `&msg`, a borrow of a local `String`, to `context`?
    No. The message type must be `'static` because the `anyhow::Error` may outlive the function. A `&String` borrowed from a local fails with error[E0597], "`msg` does not live long enough". Pass the `String` by value, a `&'static str` literal, or build it inside `with_context`.
  • What does `.context(...)` do on an `Option`?
    anyhow implements its `Context` trait for `Option<T>` too. `Some(v)` becomes `Ok(v)` and `None` becomes an `anyhow::Error` whose message is your context. There is no underlying cause in that case, so the chain has a single entry, which is fine for a missing configuration key.

  • Adding context replaces the io::Error, so its error kind is lost.
  • context and with_context behave the same; the closure is only a style choice.
  • with_context is an inherent method of Result, so no import is needed.
  • Passing a borrowed local string as the context message is fine because it is only printed.
  • Only a custom error enum can attach a file path to an io::Error.
open as a page

In Rust, what decides whether std::backtrace::Backtrace::capture records a stack, and how do RUST_BACKTRACE and RUST_LIB_BACKTRACE differ?

level: middleimportance: must knowfreq 50%

basics

~20 s

Backtrace::capture checks RUST_LIB_BACKTRACE first, then RUST_BACKTRACE; a value of 0 disables it, any other value enables it, and neither set means disabled. The default panic hook reads only RUST_BACKTRACE, so RUST_LIB_BACKTRACE controls error backtraces separately.

open as a page

When a Rust program prints an anyhow::Error, how do {}, {:#}, {:?} and {:#?} differ, and which does main use?

level: middleimportance: should knowfreq 45%

basics

~20 s

{} prints only the outermost message; {:#} prints every layer on one line joined by colons; {:?} prints a multi-line report with Caused by: and any captured backtrace; {:#?} is a struct-style dump. Returning Err from main prints Error: plus {:?}.

open as a page

A Rust service wraps I/O errors with map_err(|e| anyhow!("failed to load {path}: {e}")); why does downcast_ref::<io::Error>() now return None?

level: seniorimportance: should knowfreq 30%

basics

~20 s

anyhow! with a format string builds an error from the formatted text alone, so the io::Error is converted to a String and dropped. Its kind, code and place in the chain are gone; with_context(|| format!("failed to load {path}")) keeps it as the source.

open as a page

A Rust deploy tool logs each anyhow error at every layer before returning it with ?; why is that worse, and where should it log?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Logging and then returning with ? writes one fragment per layer, often with {} so the root cause never appears. Lower layers should only add context and propagate; the boundary that handles the error logs it once, with {:#} or {:?}.

open as a page