gpt4 book ai didi

rust - `?` 不能 't convert the error to ` std::io::Error`

转载 作者:行者123 更新时间:2023-12-03 11:25:01 25 4
gpt4 key购买 nike

我正在尝试使用 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)

上面的代码块导致编译错误:
`?` couldn't convert the error to `std::io::Error` the trait ` 
`std::convert::From<reqwest::error::Error>` is not implemented for `std::io::Error`

我不明白为什么会收到此错误。我已经使我的代码尽可能接近示例。如果我删除 ? 它将编译和 res.status .但我需要获得状态 res.status值(value)。更重要的是,我需要了解我错过了什么或做错了什么。

最佳答案

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

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

fn main() -> Result<(), std::io::Error> {
// ...
}

问题是 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(())
}

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

更新:
评论中指出,exifailure 已弃用依赖项,这可以在没有外部 crate 的情况下实现。有一种返回封装动态错误的推荐方法: 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(())

}

从我可以看到从 main 返回聚合错误的行为是相同的。

关于rust - `?` 不能 't convert the error to ` std::io::Error`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62273768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com