rust / expert
Snippet
Capturing Dynamic Execution Backtraces in Custom Errors
Demonstrates how to capture call stacks at the exact point of error creation using Rust's standard library Backtrace type, providing debugging capabilities without third-party frameworks.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use std::backtrace::Backtrace;use std::fmt;#[derive(Debug)]pub struct EngineError {pub message: String,pub backtrace: Backtrace,}impl EngineError {pub fn new(msg: impl Into<String>) -> Self {Self {message: msg.into(),backtrace: Backtrace::capture(),}}}impl fmt::Display for EngineError {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {write!(f, "Engine Error: {}\nBacktrace:\n{}", self.message, self.backtrace)}}impl std::error::Error for EngineError {}
Breakdown
1
pub backtrace: Backtrace,
Fields the standard Backtrace struct to capture program stack traces.
2
backtrace: Backtrace::capture(),
Dynamically captures the current execution context and call stack frame pointers.
3
impl fmt::Display for EngineError {
Implements formatting to print the user-friendly message along with the stack trace.
4
impl std::error::Error for EngineError {}
Implements the core Error trait, enabling compatibility with standard result propagation.