Skip to content

Instantly share code, notes, and snippets.

@oconnor663
Created May 28, 2025 17:45
Show Gist options
  • Save oconnor663/5710fa8aa9f868ffab42fe8dbeb077c9 to your computer and use it in GitHub Desktop.
Save oconnor663/5710fa8aa9f868ffab42fe8dbeb077c9 to your computer and use it in GitHub Desktop.
playing with anyhow and downcasting
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
}
@oconnor663
Copy link
Author

Current output:

Looks like we hit a foo error: FooError
Error: bar trying to foo

Caused by:
    foo error!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment