Error Context & Backtraces
Attach context as errors bubble up. Enable backtraces (RUST_BACKTRACE=1) for panic and some error types to locate failure origins.
Busca en todas las páginas de la documentación
Attach context as errors bubble up. Enable backtraces (RUST_BACKTRACE=1) for panic and some error types to locate failure origins.
use anyhow::Context;
fn load(path: &str) -> anyhow::Result<String> {
std::fs::read_to_string(path)
.with_context(|| format!("failed to read config at {path}"))
}When to reach for this: Production debugging - know what operation failed, not only low-level cause.
fn pipeline(cfg_path: &str) -> anyhow::Result<u16> {
let raw = load(cfg_path)?;
let port: u16 = raw.trim().parse().context("port must be integer")?;
Ok(port)
}
fn main() {
if let Err(e) = pipeline("missing.toml") {
eprintln!("Error: {e:#}");
for cause in e.chain() {
eprintln!(" caused by: {cause}");
}
}
}What this demonstrates:
{e:#} alternate display with causesstd::backtrace::Backtrace capture on nightly/stable features varies - RUST_BACKTRACE=1 for panics. anyhow backtrace feature adds to errors.
#[source] attribute on variants.| Alternative | Use When | Don't Use When |
|---|---|---|
| Structured tracing | Production observability | Simple CLI |
snafu context | Typed contexts | anyhow simplicity |
| Manual match logging | Full control | Verbose |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026