Skip to content

Instantly share code, notes, and snippets.

@ShabbirHasan1
Forked from mikeando/thiserror_backtrace.rs
Created April 19, 2025 07:51
Show Gist options
  • Save ShabbirHasan1/55b1d3e5943928e0f2d32f780cd300a5 to your computer and use it in GitHub Desktop.
Save ShabbirHasan1/55b1d3e5943928e0f2d32f780cd300a5 to your computer and use it in GitHub Desktop.
Example of backtrace usage in thiserror
#![feature(backtrace)]
extern crate thiserror;
use thiserror::Error;
use std::backtrace::Backtrace;
#[derive(Error, Debug)]
pub enum DataStoreError {
//#[error("data store disconnected")]
//Disconnect(#[from] io::Error),
#[error("the data for key `{0}` is not available")]
Redaction(String),
#[error("invalid header (expected {expected:?}, found {found:?})")]
InvalidHeader {
expected: String,
found: String,
backtrace: Backtrace,
},
#[error("unknown data store error")]
Unknown,
}
pub fn explode() -> Result<(),DataStoreError> {
Err(DataStoreError::InvalidHeader { expected: "A".to_owned(), found: "B".to_owned(), backtrace: Backtrace::force_capture() })
}
fn main() {
use std::error::Error;
let e = explode().err().unwrap();
let b = e.backtrace();
println!("e = {}", e);
println!("b = {:?}", b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment