Skip to content

Instantly share code, notes, and snippets.

@phildawes
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phildawes/6759ba24a8a2f2baf68f to your computer and use it in GitHub Desktop.
Save phildawes/6759ba24a8a2f2baf68f to your computer and use it in GitHub Desktop.
backtrace in Error
#![feature(std_misc)]
#![feature(unmarked_api)]
use std::rt::backtrace;
use std::path::PathBuf;
use std::result::Result;
use std::error::Error;
pub type MResult<T> = std::result::Result<T, MyError>;
#[derive(Debug,Clone)]
pub struct MyError {
desc: String,
backtrace: String
}
fn get_backtrace() -> String {
let mut m = Vec::new();
backtrace::write(&mut m).ok().
map_or("No backtrace".to_string(),
|_| String::from_utf8_lossy(&m).to_string())
}
impl<T:std::error::Error> From<T> for MyError {
fn from(e: T) -> MyError {
MyError { desc: e.description().to_string(),
backtrace: get_backtrace()
}
}
}
fn doit() -> MResult<String> {
let f = [-1;15];
let s = try!(std::str::from_utf8(&f));
Ok(s.to_string())
}
fn main() {
let res = doit(); // should error
let s = match res {
Ok(s) => s,
Err(e) => {
println!("Got an error: {}",e.desc);
println!("{}", e.backtrace);
return;
}
};
println!("Didn't error! result was {}", s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment