skip to content

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%

answer

  1. format turns an error into text
  2. Error::msg holds a String
  3. chain of length one
  4. wrap instead of re-typing

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.

solid answer

~40 s

`anyhow!("failed to load {path}: {e}")` takes the format-string arm of the macro, which builds an error with `Error::msg` from the formatted text. The `io::Error` is rendered once through `Display`, copied into a `String` and dropped when the closure returns. So `err.chain().count()` is 1, `err.root_cause()` is the whole message, `downcast_ref::<io::Error>()` returns `None` (it would match `String`), and `{:?}` has no `Caused by:` section. Any code that branched on `io::ErrorKind` silently stops matching. The fix is to wrap rather than re-type: `.with_context(|| format!("failed to load {path}"))`, or `anyhow::Error::new(e).context(...)`, which keeps the `io::Error` as the source; and drop `{e}` from the message, since `{:#}` prints the cause anyway.

code

rust · 20 lines
rust
use anyhow::{anyhow, Context, Result};
use std::{fs, io};

fn flattened(path: &str) -> Result<String> {
    fs::read_to_string(path).map_err(|e| anyhow!("failed to load {path}: {e}"))
}

fn preserved(path: &str) -> Result<String> {
    fs::read_to_string(path).with_context(|| format!("failed to load {path}"))
}

fn main() {
    let a = flattened("deploy/prod.toml").unwrap_err();
    let b = preserved("deploy/prod.toml").unwrap_err();
    println!("flattened: chain={} io={}", a.chain().count(), a.downcast_ref::<io::Error>().is_some());
    println!("preserved: chain={} io={}", b.chain().count(), b.downcast_ref::<io::Error>().is_some());
    println!("{a:?}");
    println!("---");
    println!("{b:?}");
}

go deeper

for a junior

Recall that formatting an error into a new message copies its text, while with_context wraps the original error and keeps it.

for a middle

Explain the anyhow! macro arms: a format string goes through Error::msg and stores text, a single error expression keeps the error value.

for a senior

Diagnose the symptom from its effects: one-link chains, no Caused by:, a retry on ErrorKind that never fires, and fix it by wrapping with context instead of formatting.

for a principal

Make source preservation reviewable: flag any error variable interpolated into a new error, and test downcasts on paths where callers branch on the cause.

## What the code does A common way to "add the path" to an I/O failure looks like this: ```rust fs::read_to_string(path).map_err(|e| anyhow!("failed to load {path}: {e}")) ``` The message printed with `{}` looks right: `failed to load deploy/prod.toml: No such file or directory (os error 2)`. But a caller that later asks `err.downcast_ref::<std::io::Error>()` gets `None`, `err.chain().count()` is `1`, and `err.root_cause()` is the formatted message itself. ## Why the source is gone The `anyhow!` macro has three arms in anyhow's `macros.rs`: - `anyhow!("literal")`, including a literal with inline captured arguments such as `{path}` and `{e}`, goes through `format_err`, which builds the error from the formatted text with `Error::msg`. The new error holds a **`String`** (or a `&'static str` for a literal with no arguments), and nothing else. - `anyhow!(expr)` with a single expression that is an error value keeps that value: `anyhow!(e)` still downcasts to `io::Error`. - `anyhow!(fmt, args...)` formats into a `String`, like the first arm. So in the flattened version, `{e}` calls `io::Error`'s `Display` once, copies the text into the new message, and the `io::Error` itself is dropped when the closure returns. The structured information, the `ErrorKind` and the OS code, survives only as characters in a string. ## What breaks downstream 1. **Branching on the cause.** A retry loop that checks `io::ErrorKind::NotFound` or `ConnectionRefused` no longer matches, so it either never retries or retries everything. 2. **Root-cause reporting.** `err.root_cause()` and the last item of `err.chain()` are the whole message, so a metrics label built from the root cause becomes one unique label per path. 3. **Formatting.** `{:?}` prints a single line with no `Caused by:` section, and `{:#}` cannot show more layers than exist. 4. **Duplication when mixed.** If an outer layer later uses `with_context` correctly and an inner one flattened, the cause text appears in the middle of a message rather than at the end of the chain. ## The fix: wrap, don't re-type | Approach | Source kept? | `downcast_ref::<io::Error>()` | |---|---|---| | `map_err` into `anyhow!` with a format string that interpolates `{e}` | no, text copy only | `None` | | `with_context` with a closure returning `format!("failed to load {path}")` | yes | `Some` | | `map_err` into `anyhow::Error::new(e)` followed by `.context(...)` | yes | `Some` | | `map_err` into `anyhow!(e)` with the error as the only argument | yes, but no added message | `Some` | `with_context` (from the `anyhow::Context` trait) is the idiomatic choice. It stores the closure's message as a new outer layer and keeps the original error as that layer's source. Note that the context message should **not** repeat `{e}`: the cause is printed by `{:#}` and `{:?}` already, so including it again prints it twice. anyhow's documentation adds a detail that matters here: for an error with context, `downcast_ref` succeeds for either the context type or the type of the error the context was attached to. That is why the preserved version still finds the `io::Error`. ## The same defect elsewhere The flattening is not specific to anyhow. A hand-written error type that stores `e.to_string()` instead of the error, or that returns `None` from `std::error::Error::source`, cuts the chain the same way; designing such types is covered with custom error types. A typed library error that should carry its cause holds the cause as a field and returns it from `source()`. ## Review heuristics - Flag any `format!` or `anyhow!` that interpolates an error variable, such as `{e}` or `{err}`, into a new error. That is almost always a lost source. - Prefer `with_context` over `map_err` whenever the goal is to add words, not to change the error's type. - In tests, assert on `downcast_ref` or `chain().count()` for paths whose callers branch on the cause, so a regression to flattening fails loudly. - Keep `anyhow!` for errors that genuinely start in your code (a validation failure with no underlying error), where a message is all there is. - When a flattened error has already shipped, look for symptoms in logs and dashboards: error messages that embed `(os error N)` in the middle of a sentence, a `Caused by:` section that never appears, and retry or fallback branches whose counters stay at zero.

  • Does `anyhow!(e)` with just the error value also lose the source?
    No. The single-expression arm of `anyhow!` dispatches on the argument's type, and for a value that implements `std::error::Error` it keeps that value, so `downcast_ref::<io::Error>()` still succeeds. Only the format-string arms build a message-only error.
  • After flattening, what can `downcast_ref` still find?
    The message itself. anyhow builds the error with `Error::msg`; for a literal with interpolated arguments that stores a `String`, so `downcast_ref::<String>()` returns `Some`. That is text, not structure: no `ErrorKind`, no OS code.
  • Why should the context message not include `{e}` once you switch to `with_context`?
    The cause is now a separate link in the chain, and `{:#}` and `{:?}` print it. Interpolating it into the context as well prints the same text twice, which makes logs longer and harder to scan.

Retyping a letter into your own memo versus stapling a cover note to the original: the memo reads the same, but the original letter, with its letterhead and reference number, is no longer there for anyone who needs it.

  • Interpolating {e} into anyhow! keeps the io::Error as the source.
  • downcast_ref returning None means the error was never an io::Error.
  • anyhow!(e) with only the error value also turns it into a string.
  • The message already contains the cause, so nothing useful was lost.
  • map_err and with_context are interchangeable for adding a path to an error.