liveBook · Manning

Stack trace

As explained in Learn Rust in a Month of Lunches

A backtrace is a record of the call stack showing the sequence of function calls leading to a program point or failure.

A stack trace, called a backtrace in Rust, records the function calls leading to a program point or failure. When a test panics, it can show the path from Rust’s runtime code back to your own function and source line. Read the entries from the bottom upward to find where your code triggered the problem. section 14.2.2

Use a backtrace when the ordinary panic or test output does not reveal the cause:

  • Enable RUST_BACKTRACE=1 for a shorter trace, or RUST_BACKTRACE=full for a more detailed one. section 14.2.2
  • Capture one during execution with std::backtrace::Backtrace::capture(). section 21.3
  • Check BacktraceStatus to distinguish Disabled, Captured, and Unsupported before displaying it. section 21.3
  • Remember that RUST_LIB_BACKTRACE or RUST_BACKTRACE values other than 0 enable capture for the runtime API. section 21.3

Finding the failing line

If a failing assertion reports `playground::two_is_two` at `src/lib.rs:3:5`, that entry points to the test code that triggered the panic. The surrounding runtime entries are usually less useful for locating your bug. section 14.2.2

use std::{
    backtrace::{Backtrace, BacktraceStatus::*},
    panic,
};
 
fn main() {
    panic::set_hook(Box::new(|_| {
        println!("Panicked! Trying to get a backtrace...");
        let backtrace = Backtrace::capture();                            #1
        match backtrace.status() {                                       #2
            Disabled => println!("Backtrace isn't enabled, sorry"),
            Captured => println!("Here's the backtrace!!\n{backtrace}"),
            Unsupported => println!("No backtrace possible, sorry"),     #3
            // Do some database shutting down stuff 
        }
    }));
 
    std::env::set_var("RUST_BACKTRACE", "0");                            #4
    panic!();
}

This example combines a panic hook, runtime capture, environment-based enablement, and status handling. section 21.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains output reading, environment configuration, runtime capture, and status handling without developing tracing internals.
Examples
Uses failed Rust assertions, RUST_BACKTRACE settings, Backtrace::capture(), and BacktraceStatus matching.
What you can do after
Diagnose/debug with Rust backtraces by enabling capture, locating application frames, and handling unavailable traces.
How it connects
Connects backtraces with panics, assertions, environment variables, panic hooks, and the standard library.

Also explained in

Compare how 7 books explain stack trace →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.