Created
December 2, 2018 14:53
-
-
Save dumindu/73cd89957e24713b91cb30ed22e2526a 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::fmt; | |
struct CustomErr(isize); | |
// Implement std::fmt::Display for CustomErr | |
impl fmt::Display for CustomErr { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "{}", self.user_face_err()) | |
} | |
} | |
// Implement std::fmt::Debug for CustomErr | |
impl fmt::Debug for CustomErr { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "{}", self.programmer_face_err()) | |
} | |
} | |
impl CustomErr { | |
// Handle user-facing output | |
fn user_face_err(&self) -> &str { | |
let CustomErr(err_code) = self; | |
let err_msg = match err_code { | |
404 => "Sorry, Can not find the Page!", | |
_ => "Sorry, something is wrong! Please Try Again!", | |
}; | |
err_msg | |
} | |
// Handle programmer-facing output | |
fn programmer_face_err(&self) -> &str { | |
let CustomErr(err_code) = self; | |
let err_msg = match err_code { | |
404 => "CustomErr {{ code: 404, message: Not found }}", | |
_ => "CustomErr {{ code: n/a }} ", | |
}; | |
err_msg | |
} | |
} | |
// A sample function to produce an CustomErr Err | |
fn produce_error() -> Result<(), CustomErr> { | |
Err(CustomErr(404)) | |
} | |
fn main() { | |
match produce_error() { | |
Err(e) => eprintln!("{}", e), // Sorry, Can not find the Page! | |
_ => println!("No error"), | |
} | |
eprintln!("{:?}", produce_error()); // Err(CustomErr {{ code: 404, message: Not found }}) | |
eprintln!("{:#?}", produce_error()); | |
// Err( | |
// CustomErr {{ code: 404, message: Not found }} | |
// ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment