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.
Code
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
Resultyou 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.HTTP Header AnalyzerPaste raw HTTP header lines and get a parsed name-value list with plain-language notes for common headers and security observations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.