anyhow::Error as source for custom_error

I'm trying to contribute to a project that uses the custom_error crate, but my contribution uses a library method that returns anyhow::Error.

Using custom_error, things usually look something like this:

custom_error! {pub SomeModuleError
    Specific1{source: AnotherCustomError} = "Some issue: {source}",
    Specific2{source: serde_json::Error } = "Malformed JSON: {source}",
}

If I try to use anyhow::Error as the source for an error like those above, I get the following:

the trait bound `anyhow::Error: custom_error::Error` is not satisfied
required for the cast from `anyhow::Error` to the object type `dyn custom_error::Error`

The following works:

use thiserror::Error;

#[derive(Debug, Error)]
pub enum MyContributionError {
    #[error("Error issue")]
    Contribution(#[from] anyhow::Error),
}

But can anyone tell me if I'm missing something so that I can use custom_error instead, with anyhow::Error as the source?

anyhow::Error intentionally doesn't implement the std::error::Error trait, so it can't be used inside another error in the conventional fashion. Generally, libraries should not export errors as anyhow::Error — the design of anyhow is opinionated and meant for catch-all error handling in applications.

That said, if necessary, anyhow::Error can be converted to Box<dyn Error>, which thus reveals the contained original Error implementation. (Note that Box<dyn Error> contains an Error, but does not itself implement Error; you may need to do additional work to handle that.)

2 Likes

Thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.