Skip to content

Instantly share code, notes, and snippets.

@mikeando
Created May 12, 2020 23:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeando/c03fd62e552ccabcdb894251b59038c7 to your computer and use it in GitHub Desktop.
Save mikeando/c03fd62e552ccabcdb894251b59038c7 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);
}
@hasezoey
Copy link

hasezoey commented Jun 2, 2023

this code does not seem valid anymore in current rust (1.69) since about 1.65 where std::backtrace::Backtrace was stabilized but now does not have any method named .backtrace() anymore, also requires to use #![feature(error_generic_member_access)] and #![feature(provide_any)] the updated part would look something like:

// instead of e.backtrace();
let b = std::any::request_ref::<std::backtrace::Backtrace>(&e);
// but request_ref now returns a Option instead of always a Backtrace

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment