-
-
Save rust-play/a15a291c4c47f00f699e392ce6b6b2d0 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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::Error; | |
#[derive(Debug)] | |
struct CustomError(String); | |
impl Error for CustomError {} | |
impl std::fmt::Display for CustomError { | |
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { | |
<Self as std::fmt::Debug>::fmt(self, f) // delegate to Debug | |
} | |
} | |
impl CustomError { | |
pub fn shout(&self) { | |
println!("{}", self.0); | |
} | |
} | |
fn boom() -> Result<(), Box<dyn Error>> { | |
// Err(String::from("string error").into()) | |
Err(Box::new(CustomError("custom error".to_owned()))) | |
} | |
fn main() { | |
let e = boom().unwrap_err(); | |
if let Some(e) = e.downcast_ref::<CustomError>() { | |
e.shout(); | |
} else { | |
println!("Other: {}", e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment