lost.sof
lost.sof

Reputation: 261

how to convert anyhow error to std error?

I am new to anyhow and I would like to know if there is a way to convert anyhow error to std error

code

fn m() {
    let a: anyhow::Result<String> = Ok("".into());
    n(a);
}

fn n(r: std::result::Result<String, impl std::error::Error>) {
    println!("{:?}", r);
}

error msg

error[E0277]: the trait bound `anyhow::Error: std::error::Error` is not satisfied
  --> src\main.rs:82:7
   |
82 |     n(a);
   |     - ^ the trait `std::error::Error` is not implemented for `anyhow::Error`
   |     |
   |     required by a bound introduced by this call

Upvotes: 7

Views: 5263

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70990

Use the Deref or AsRef impl:

match a {
    Ok(v) => n(Ok::<_, &dyn std::error::Error>(v)),
    Err(e) => n(Err::<_, &dyn std::error::Error>(e.as_ref())),
}
// Or
match a {
    Ok(v) => n(Ok::<_, &dyn std::error::Error>(v)),
    Err(e) => n(Err::<_, &dyn std::error::Error>(&*e)),
}

Upvotes: 6

Related Questions