Capture Backtraces With std::backtrace

Capture the current call stack with std::backtrace::Backtrace and inspect its frames to enrich error reports without extra crates.

RustResilience

Code

rustsnippet
27 lines
use std::backtrace::Backtrace;

fn load_config() -> Result<(), String> {
    Err("config file missing".to_string())
}

fn start() -> Result<(), String> {
    // 出错点捕获回溯,保留调用链
    load_config().map_err(|message| {
        let trace = Backtrace::capture();
        format!("{message}\n--- backtrace ---\n{trace}")
    })
}

fn main() {
    match start() {
        Ok(()) => println!("started"),
        Err(report) => {
            println!("startup failed");
            // 默认可能只显示 disabled,需要 RUST_BACKTRACE=1
            println!("captured: {}", Backtrace::capture().status());
            println!("frames available: {}", Backtrace::capture().frames().len());
            let first_line = report.lines().next().unwrap_or("no details");
            println!("first line: {first_line}");
        }
    }
}

How it works

Capture Backtraces With std::backtrace reduces to the functions load_config, start and main.

Failure is encoded in the return type — Result leaves no room for an unhandled error. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Points of care

  • Every fallible call yields a Result you must unwrap or propagate; there is no implicit throw.

Using it

Entry signature: fn load_config() -> Result<(), String>

The run emits 5 labeled sections — started, startup failed, captured:, frames available:, first line: — one per step.

There are 1 call inside main — start — executed top to bottom.

Key statements

let first_line = report.lines().next().unwrap_or("no details");
fn load_config() -> Result<(), String> {
    Err("config file missing".to_string())
}
fn start() -> Result<(), String> {
    // 出错点捕获回溯,保留调用链
    load_config().map_err(|message| {
        let trace = Backtrace::capture();
        format!("{message}\n--- backtrace ---\n{trace}")
    })
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
Through the type system: failures are `Result` variants the caller must consume.
What does Capture Backtraces With std::backtrace print when run?
No setup needed: run the file and look for labeled lines like `started`, `startup failed`, `captured:` in the output.