I am confused about a problem, the code snippet as following.
The playgroud link is here
// I define a customed error here
#[derive(Debug)]
struct UserErr<'a> (&'a str);
impl std::fmt::Display for UserErr<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
write!(f, "UserError: {}", self.0)
}
}
impl std::error::Error for UserErr<'_> {}
use tokio;
use reqwest;
#[tokio::main]
async fn main()-> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
client.get("http://google.com").send().await?;
Err(Box::new(UserErr("error occur")))
// Ok(())
}
There code compile error:
|
16 | client.get("http://google.com").send().await?;
| ^ the trait `From<reqwest::Error>` is not implemented for `Box<UserErr<'_>>`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= help: the following implementations were found:
<Box<(dyn std::error::Error + 'a)> as From<E>>
<Box<(dyn std::error::Error + 'static)> as From<&str>>
<Box<(dyn std::error::Error + 'static)> as From<Cow<'a, str>>>
<Box<(dyn std::error::Error + 'static)> as From<String>>
and 22 others
= note: required by `from`
|
14 | async fn main()-> Result<(), Box<dyn std::error::Error>> {
| -------------------------------------- expected `Result<(), Box<(dyn std::error::Error + 'static)>>` because of return type
...
17 | Err(Box::new(UserErr("error occur")))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected trait object `dyn std::error::Error`, found struct `UserErr`
|
= note: expected enum `Result<(), Box<(dyn std::error::Error + 'static)>>`
found enum `Result<_, Box<UserErr<'_>>>`
But I have impl std::error::Error
for UserErr
, why this error?
When I change code to
//Err(Box::new(UserErr("error occur")))
Ok(())
Everythings is ok. I am confused about that.
Pls help, thanks.