Created
October 1, 2015 22:27
-
-
Save phil-n/319958ef7a961620179e to your computer and use it in GitHub Desktop.
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
use std::error; | |
use std::num; | |
use std::fmt; | |
use std::io; | |
fn main() { | |
let r = read_i32(); | |
match r { | |
Ok(i) => println!("{}", i), | |
Err(e) => println!("{}", e) | |
} | |
} | |
fn read_i32() -> Result<i32, MyError> { | |
let mut buf = String::new(); | |
println!("Please enter a number"); | |
try!(std::io::stdin().read_line(&mut buf)); | |
let i = try!(buf.trim().parse::<i32>()); | |
Ok(i) | |
} | |
#[derive(Debug)] | |
enum MyError { | |
IoError(io::Error), | |
ParseError(num::ParseIntError) | |
} | |
impl fmt::Display for MyError { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "MyError: {}", (self as &error::Error).description()) | |
} | |
} | |
impl error::Error for MyError { | |
fn description(&self) -> &str { | |
match *self { | |
MyError::ParseError(_) => "Failed to parse", | |
MyError::IoError(_) => "Failed to read" | |
} | |
} | |
fn cause(&self) -> Option<&error::Error> { | |
match *self { | |
MyError::ParseError(ref pe) => Some(pe), | |
MyError::IoError(ref ioe) => Some(ioe), | |
} | |
} | |
} | |
impl From<std::num::ParseIntError> for MyError { | |
fn from(err: std::num::ParseIntError) -> MyError { | |
MyError::ParseError(err) | |
} | |
} | |
impl From<io::Error> for MyError { | |
fn from(err: io::Error) -> MyError { | |
MyError::IoError(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment