Skip to content

Instantly share code, notes, and snippets.

@Leedehai
Last active April 22, 2024 16:00
Show Gist options
  • Save Leedehai/583099e1e998d0eca13c444d59f454e2 to your computer and use it in GitHub Desktop.
Save Leedehai/583099e1e998d0eca13c444d59f454e2 to your computer and use it in GitHub Desktop.
Backtrace in Rust without panicking
// [depdendencies]
// backtrace = "0.3" # https://docs.rs/crate/backtrace/latest
fn backtrace(level: usize) {
let (trace, curr_file, curr_line) = (backtrace::Backtrace::new(), file!(), line!());
let symbols = trace
.frames()
.iter()
.flat_map(backtrace::BacktraceFrame::symbols)
.skip_while(|s| {
s.filename().map(|p| !p.ends_with(curr_file)).unwrap_or(true)
|| s.lineno() != Some(curr_line)
});
println!("backtrace() is called from..");
for (i, sym) in symbols.enumerate() {
if i > level {
break;
}
println!(
"{i}: {:?}:{:?}\n\t\x1b[2m{:?}\x1b[0m",
backtrace::BacktraceSymbol::filename(sym)
.unwrap_or(std::path::Path::new("(none)")),
backtrace::BacktraceSymbol::lineno(sym).unwrap_or(0),
backtrace::BacktraceSymbol::name(sym),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment