TIL: #[track_caller] gives panics the right line number

Put #[track_caller] on a helper that can panic, and the panic message points at the code that called it instead of the helper itself.

1 min read

A small helper that unwraps with context is handy, but its panics all point to the same line inside the helper.

rust
#[track_caller]
fn expect_env(name: &str) -> String {
    std::env::var(name).unwrap_or_else(|_| panic!("missing env var {name}"))
}

With #[track_caller], std::panic::Location::caller() and the panic message report where expect_env was called. It costs nothing when nothing panics.

This post only exists in English. The French blog does not list it, and the language switch on this page leads to the French home page.

Written by

Software, backend and DevOps engineer. I write Rust, run Kubernetes and measure everything with OpenTelemetry.

↑↓ navigate ↵ open Esc close