skip to content

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

level: middleimportance: should knowfreq 45%

answer

  1. Display vs Debug
  2. the alternate # flag
  3. Caused by: section
  4. Termination for Result

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 {:?}.

solid answer

~40 s

`anyhow::Error` implements `Display` and `Debug`, each with a plain and an alternate (`#`) form. `{}` shows only the outermost message, such as `cannot deploy prod`. `{:#}` walks the chain on one line: `cannot deploy prod: failed to read deploy/prod.toml: No such file or directory (os error 2)`. `{:?}` prints the outer message, then a `Caused by:` list (numbered when there are several causes), then `Stack backtrace:` if one was captured. `{:#?}` is a struct-style `Error { context: ..., source: ... }` dump. When `main` returns `anyhow::Result<()>` and fails, std's `Termination` impl for `Result` writes `Error: ` plus the `{:?}` form to stderr and exits with a failure status.

code

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

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

fn deploy(env: &str) -> Result<()> {
    let path = format!("deploy/{env}.toml");
    read_manifest(&path).with_context(|| format!("cannot deploy {env}"))?;
    Ok(())
}

fn main() -> Result<()> {
    let err = deploy("prod").unwrap_err();
    println!("{err}");
    println!("{err:#}");
    println!("{err:?}");
    println!("{err:#?}");
    deploy("prod") // returning Err from main prints "Error: " + {:?}
}

go deeper

for a junior

Recall that {} gives only the top message and {:#} gives the whole chain on one line; that difference decides whether a log line names the root cause.

for a middle

Explain the Display and Debug forms, the alternate flag, the Caused by: layout, and that main's Termination impl prints Error: plus the Debug form.

for a senior

Pick formats deliberately: {:#} for line-oriented logs, {:?} for CLI stderr, chain() for structured fields, and keep backtraces out of client-facing text.

for a principal

Treat error rendering as part of the operability contract: a team-wide rule on which format reaches logs, users and alerts avoids both lost causes and leaked internals.

## Two kinds of formatting, two variants each An `anyhow::Error` implements both `std::fmt::Display` and `std::fmt::Debug`, and anyhow gives each of them a plain and an **alternate** form. The alternate form is what the `#` flag in a format string selects (`{:#}` and `{:#?}`); inside an implementation it is visible as `Formatter::alternate()`. anyhow's `fmt.rs` branches on exactly that flag. Take a deploy tool where `deploy("prod")` adds the context `cannot deploy prod`, an inner function adds `failed to read deploy/prod.toml`, and the root cause is the `io::Error` `No such file or directory (os error 2)`. | Format | Output shape | Use it for | |---|---|---| | `{}` / `to_string()` | only the outermost message: `cannot deploy prod` | a short headline, a user-facing title | | `{:#}` | every layer on one line, joined by `: ` | a single log line that still names the root cause | | `{:?}` | outermost message, a `Caused by:` list when there are causes, then `Stack backtrace:` if one was captured | stderr from a CLI, a detailed log entry | | `{:#?}` | a struct-style dump: `Error { context: ..., source: ... }` | debugging the error value itself | ## What each one actually prints **`{}`** prints the `Display` of whatever the `anyhow::Error` was built from: for a context-wrapped error, the context message. None of the lower causes appears. That is the most common surprise: a log line written with `{}` says `cannot deploy prod` and nothing about the missing file. **`{:#}`** walks the cause chain, skipping the first entry it already printed, and writes `: ` followed by each cause: `cannot deploy prod: failed to read deploy/prod.toml: No such file or directory (os error 2)`. **`{:?}`** prints the outer message; if the error has a source, it then prints a blank line, `Caused by:`, and each cause indented. With more than one cause, the entries are numbered `0:`, `1:`, ...; with a single cause the entry is only indented. If a backtrace was captured (see the environment variables `RUST_BACKTRACE` and `RUST_LIB_BACKTRACE`), a `Stack backtrace:` section follows. **`{:#?}`** does not use that layout at all. It delegates to the `Debug` impl of the object anyhow stores, which for a context layer is a struct with `context` and `source` fields, nesting down to the `io::Error`'s own `Os { code: 2, kind: NotFound, message: ... }`. ## Why `main` gives you the `{:?}` form `fn main() -> anyhow::Result<()>` works because std implements `std::process::Termination` for `Result<T, E>` where `E: Debug`. When `main` returns `Err(err)`, that implementation writes `Error: ` followed by `err` formatted with `{:?}` to stderr and reports a failure exit status. For an `anyhow::Error` that is the multi-line report with `Caused by:`, which is why anyhow's documentation calls `{:?}` the representation you get by default from `main`. The same mechanism is less helpful for other error types: - A `Box<dyn std::error::Error>` returned from `main` prints that error's own `Debug`, usually a derived struct dump, because std does not walk `source()` for you on stable. - std has an error reporter type, `std::error::Report`, that renders a chain; it is still **unstable**, so on stable Rust you either use anyhow's formatting or loop over `source()` yourself. ## Walking the chain yourself When neither layout fits (structured logging, an HTTP error body, a metrics label), use the chain directly: 1. `err.chain()` iterates from the outermost layer down to the root cause, each item a `&(dyn std::error::Error + 'static)`. 2. `err.root_cause()` returns the last item of that iterator. 3. `cause.downcast_ref::<std::io::Error>()` on any item lets you inspect a specific type, for example to read an `io::ErrorKind`. ## Common mistakes - Logging with `{}` and losing every cause below the first. - Writing the cause into the context string (`"failed to read {path}: {e}"`) and then printing with `{:#}`, so the cause appears twice. - Expecting `{:#?}` to be a prettier `{:?}`; it is a different, struct-style output. - Expecting the backtrace in `{:#}`; only the plain `{:?}` form appends it. - Showing `{:?}` to an end user or an untrusted client: it can include file paths from the backtrace and internal messages. Keep the full report for logs and give users the `{}` headline.

  • What changes in the `{:?}` output when `RUST_LIB_BACKTRACE=1` is set?
    anyhow captures a `std::backtrace::Backtrace` when the error is first created, and the plain `{:?}` form appends a `Stack backtrace:` section after the causes. `{}` and `{:#}` never include it, and `{:#?}` shows the struct dump instead of the report layout.
  • How do you get the same chain from a `Box<dyn std::error::Error>` on stable Rust?
    Loop over `source()`: print the error, then `let mut cur = err.source(); while let Some(c) = cur { ...; cur = c.source(); }`. Returning the box from `main` only prints its own `Debug`, and std's chain-rendering `std::error::Report` type is still unstable.

  • Printing an anyhow::Error with {} shows the full chain of causes.
  • {:#?} is just a prettier version of the {:?} Caused by: report.
  • Returning Err from main prints the error's Display, so the causes are lost.
  • The backtrace appears in every format, including {:#}.
  • std::error::Report is the stable way to print a source chain today.