Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dumindu/73cd89957e24713b91cb30ed22e2526a to your computer and use it in GitHub Desktop.
Save dumindu/73cd89957e24713b91cb30ed22e2526a to your computer and use it in GitHub Desktop.
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