eyre: Converting from anyhow::Error

Hi, I am porting multiple crates from anyhow to eyre, so I have code that looks something like this:

fn foo() -> Result<(), anyhow::Error> {
  Ok(())
}

fn bar() -> Result<(), eyre::Report> {
  let f = foo().map_err(|e| eyre::Report::new(e))?;
  Ok(())
}

This, as expected, gives

error[E0277]: the trait bound `anyhow::Error: std::error::Error` is not satisfied
  --> src/lib.rs:6:49
   |
6  |     let f = foo().map_err(|e| eyre::Report::new(e))?;
   |                                                 ^ the trait `std::error::Error` is not implemented for `anyhow::Error`
   |
  ::: /home/akshayn/.cargo/registry/src/github.com-1ecc6299db9ec823/eyre-0.6.0/src/error.rs:21:12
   |
21 |         E: StdError + Send + Sync + 'static,
   |            -------- required by this bound in `eyre::error::<impl eyre::Report>::new`

error: aborting due to previous error

Since anyhow::Error and eyre::Report are so similar, is there a better way to construct an eyre::Report mid-stack than this, which is sad and throws out the context:

fn foo() -> Result<(), anyhow::Error> {
  Ok(())
}

fn bar() -> Result<(), eyre::Report> {
  let f = foo().map_err(|e| eyre::eyre!("{:?}", e))?;
  Ok(())
}

Thanks for the help!

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 1
  • Comments: 15 (5 by maintainers)

Most upvoted comments

Just for future readers:

foo().map_err(|err| eyre!(Box::new(err))

This is not permitted by Rust’s orphan rules, unfortunately.

It is permitted. The From impls you would want are:

impl<E> From<E> for Report
where
    E: Into<anyhow::Error>,
    Result<(), E>: anyhow::Context<(), E>,
{
    fn from(error: E) -> Self {
        let anyhow_error: anyhow::Error = error.into();
        let boxed_error: Box<dyn StdError + Send + Sync + 'static> = anyhow_error.into();
        Report::from_boxed(boxed_error)
    }
}

impl From<Report> for anyhow::Error {
    fn from(report: Report) -> Self {
        let boxed_error: Box<dyn StdError + Send + Sync + 'static> = report.into();
        anyhow::Error::from_boxed(boxed_error)
    }
}

This would provide ? in both directions.

I would also be interested in that. Some other coded in my project uses anyhow and manually mapping the errors is quite a pain…

though you’ll still lose the backtrace that anyhow captured originally.

verbosity of code to convert

With both the above issues in mind, is it worth adding some code in this crate under anyhow-compat feature to add support to use ? on anyhow errors to convert them eyre errors easily?

It is additive with the existing impl.

I discussed this impl with eyre maintainers in June as part of https://github.com/eyre-rs/eyre/issues/177; not sure whether there’s since then come up a reason not to implement it.

What’s the status of this feature? I would like to use ? on anyhow results on functions which return eyre::Result.

that makes sense, thanks!