This is a reference to help answer this question: โ€œwhat will my Rust program print if something goes wrong?โ€

The examples were compiled with Rust 1.76.0. All output in these examples goes to stderr, nothing goes to stdout.

Setup code for anyhow with context 2x

use anyhow::Context;

fn make_error() -> Result<(), anyhow::Error> {
    Ok(std::fs::remove_file("/this/file/does/not/exist")
        .context("oh no")
        .context("second context")?)
}

Debug

fn main() {
    eprintln!("{:?}", make_error().unwrap_err())
}
second context

Caused by:
    0: oh no
    1: No such file or directory (os error 2)

Display

fn main() {
    eprintln!("{}", make_error().unwrap_err())
}
second context

Alternate Display

fn main() {
    eprintln!("{:#}", make_error().unwrap_err())
}
second context: oh no: No such file or directory (os error 2)

Unwrap

fn main() {
    make_error().unwrap();
}
thread 'main' panicked at src/bin/anyhow_context_2x_unwrap.rs:10:18:
called `Result::unwrap()` on an `Err` value: second context

Caused by:
    0: oh no
    1: No such file or directory (os error 2)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Expect

fn main() {
    make_error().expect("oh no");
}
thread 'main' panicked at src/bin/anyhow_context_2x_expect.rs:10:18:
oh no: second context

Caused by:
    0: oh no
    1: No such file or directory (os error 2)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Return

fn main() -> Result<(), anyhow::Error> {
    make_error()
}
Error: second context

Caused by:
    0: oh no
    1: No such file or directory (os error 2)