Created
May 2, 2024 18:35
-
-
Save debasishg/276db62dadc0d131136688a0116afa3c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#[derive(Debug)] | |
enum MyError { | |
Io(std::io::Error), | |
Parse(pest::error::Error<Rule>), | |
} | |
#[derive(Debug)] | |
struct StoreError(MyError); | |
impl std::fmt::Display for StoreError { | |
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { | |
write!(f, "Store error") | |
} | |
} | |
impl std::fmt::Display for MyError { | |
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { | |
write!(f, "My error") | |
} | |
} | |
impl std::error::Error for MyError {} | |
impl std::error::Error for StoreError { | |
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | |
Some(&self.0) | |
} | |
} | |
fn do_stuff(i: i32) -> Result<(), Box<dyn Error + 'static>> { | |
if i == 10 { | |
return Err(Box::new(StoreError(MyError::Io(std::io::Error::new( | |
std::io::ErrorKind::Other, | |
"I/O error", | |
))))); | |
} | |
Ok(()) | |
} | |
pub fn do_main(count: i32) { | |
match do_stuff(count) { | |
Ok(_) => println!("Success!"), | |
Err(e) => | |
match e.downcast_ref::<StoreError>() { | |
Some(store_error) => println!("Store error: {}", store_error), | |
None => println!("Error: {}", e), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment