Created
May 28, 2025 17:45
-
-
Save oconnor663/5710fa8aa9f868ffab42fe8dbeb077c9 to your computer and use it in GitHub Desktop.
playing with anyhow and downcasting
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
use anyhow::Context; | |
use std::error::Error; | |
use std::fmt; | |
#[derive(Debug)] | |
struct FooError {} | |
impl fmt::Display for FooError { | |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
write!(f, "foo error!") | |
} | |
} | |
impl Error for FooError {} | |
fn foo() -> Result<(), FooError> { | |
Err(FooError {}) | |
} | |
fn bar() -> anyhow::Result<()> { | |
foo().context("bar trying to foo")?; | |
Ok(()) | |
} | |
fn main() -> anyhow::Result<()> { | |
let result = bar(); | |
if let Err(e) = &result { | |
if let Some(foo_error) = e.downcast_ref::<FooError>() { | |
println!("Looks like we hit a foo error: {foo_error:?}"); | |
} | |
} | |
result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Current output: