`?` 无法将错误转换为 `std::io::Error`

Jim*_*eri 7 rust reqwest

我正在尝试使用 reqwest 库并遵循我在网上各个地方找到的模式来发帖:

let res = http_client.post(&url)
                          .header("Content-Type", "application/x-www-form-urlencoded")
                          .form(&form_data)
                          .send()
                          .await?;
println!("authenticate response: {}", res.status)
Run Code Online (Sandbox Code Playgroud)

上面的代码块导致编译错误:

`?` couldn't convert the error to `std::io::Error` the trait ` 
      `std::convert::From<reqwest::error::Error>` is not implemented for `std::io::Error`
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我会收到这个错误。我已经使我的代码尽可能接近示例。如果我删除?res.status. 但我需要获取状态res.status值。更重要的是,我需要了解我遗漏了什么或做错了什么。

Sim*_*son 5

您的错误是由您调用此块的函数的返回类型引起的,编译器希望返回类型为 的错误std::io::Error

从错误描述中,我得出结论你的main函数看起来像这样:

fn main() -> Result<(), std::io::Error> {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

问题是 reqwest 不返回io::Error. 这是我几个月前写的一个片段:

use exitfailure::ExitFailure;

fn main() -> Result<(), ExitFailure> {
    let res = http_client
        .post(&url)
        .header("Content-Type", "application/x-www-form-urlencoded")
        .form(&form_data)
        .send()
        .await?;

    println!("authenticate response: {}", res.status);
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

我使用exitfailure将返回的错误类型转换为人类可读的main. 我想它也会解决你的问题。

更新: 评论中指出,exifailure 已弃用依赖项,这可以在没有外部板条箱的情况下实现。有一种返回封装动态错误的推荐方法:Box<dyn std::error::Error>

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let res = http_client
        .post(&url)
        .header("Content-Type", "application/x-www-form-urlencoded")
        .form(&form_data)
        .send()
        .await?;

    println!("authenticate response: {}", res.status);
    Ok(())

}
Run Code Online (Sandbox Code Playgroud)

从我所看到的返回约定错误的行为main是相同的。

  • 特别是因为 `exitfailure` 依赖于 `failure`,这是[已弃用](https://github.com/rust-lang-nursery/failure#failure---a-new-error-management-story)。 (3认同)
  • `Box&lt;dyn Error&gt;` 是[本书推荐](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#the--operator-can-在返回结果的函数中使用)并避免额外的依赖。 (2认同)