Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 5, 2021 23:24
Show Gist options
  • Save rust-play/a15a291c4c47f00f699e392ce6b6b2d0 to your computer and use it in GitHub Desktop.
Save rust-play/a15a291c4c47f00f699e392ce6b6b2d0 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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