Last active
August 29, 2015 14:21
-
-
Save phildawes/6759ba24a8a2f2baf68f to your computer and use it in GitHub Desktop.
backtrace in Error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![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