anyhow icon indicating copy to clipboard operation
anyhow copied to clipboard

What is the most robust way of downcasting an `anyhow::Error`?

Open thomaseizinger opened this issue 2 months ago • 1 comments

I am using anyhow extensively in my application. At the outer layer of an event loop, I am then downcasting the error to check how it needs it be handled and which log-level is appropriate.

So far, I've used root_cause for this but recently, that has failed on my because I was using bail! further down but without applying any additional .context. Hence, the resulting anyhow::Error did in fact not have a source and the check never succeeded, causing the error handling to be buggy.

I then discovered the interactions of context and the is and downcast methods.

My question now is: What is the most robust way of checking whether an anyhow::Error is / contains a particular type? It seems like to cover all bases, I need to both check is and root_cause.

Type-erasure is great for ergonomics but less so if it can easily be misused or broken by a refactoring (like the removal / addition of context).

Should is be extended to also walk all sources of the original error prior to being turned into an anyhow::Error?

thomaseizinger avatar Oct 12 '25 03:10 thomaseizinger

FWIW, I've now implemented my own behaviour on top of anyhow that IMO has less foot-gun potential: https://github.com/firezone/firezone/pull/10966

thomaseizinger avatar Nov 25 '25 04:11 thomaseizinger