Skip to content

Instantly share code, notes, and snippets.

@phil-n
Created October 1, 2015 22:27
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 phil-n/319958ef7a961620179e to your computer and use it in GitHub Desktop.
Save phil-n/319958ef7a961620179e to your computer and use it in GitHub Desktop.
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