Error handling 在实现std::io::Write时处理非std::io::错误?

Error handling 在实现std::io::Write时处理非std::io::错误?,error-handling,rust,Error Handling,Rust,我试图通过HTTP实现std::io::Write,但我不确定如何处理std::io::ErrorKind中没有对应项的错误 这是一个简短的复制品: extern crate reqwest; use std::io::Write; use std::io::Result; struct HttpClient { // Some configurations (compression, certificates, timeouts) } impl Write for HttpCli

我试图通过HTTP实现
std::io::Write
,但我不确定如何处理
std::io::ErrorKind
中没有对应项的错误

这是一个简短的复制品:

extern crate reqwest;

use std::io::Write;
use std::io::Result;

struct HttpClient {
    // Some configurations (compression, certificates, timeouts)
}

impl Write for HttpClient {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let client = ::reqwest::Client::builder().build()?;
        let res = client.post("http://httpbin.org/post").body(buf).send()?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> Result<()> {
        Ok(())
    }
}
外部板条箱要求;
使用std::io::Write;
使用std::io::Result;
结构HttpClient{
//一些配置(压缩、证书、超时)
}
HttpClient的impl写入{
fn写入(&mut self,buf:&u8])->结果{
让客户端=::reqwest::client::builder().build()?;
让res=client.post(“http://httpbin.org/post“).body(buf.send()”?;
Ok(buf.len())
}
fn刷新(&mut self)->结果{
好(())
}
}
编译器响应时有2个错误:

error[E0277]:未满足特性绑定'std::io::error:std::convert::From'
-->src/main.rs:12:22
|
12 |让客户端=::reqwest::客户端::生成器().build()?;
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^未为`std::io::Error'实现特性`std::convert::From'`
|
=帮助:找到了以下实现:
=注意:`std::convert::From::From'需要`
错误[E0277]:未满足特性绑定'std::io::error:std::convert::From'
-->src/main.rs:13:19
|
13 | let res=客户机.post(“http://httpbin.org/post“).body(buf.send()”?;
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ std::io::Error未实现特征“std::convert::From”`
|
=帮助:找到了以下实现:
=注意:`std::convert::From::From'需要`
我可以做几件事,但我对其中任何一件都不满意:

  • 使用
    map\u err
    reqwest::Error
    映射到
    std::io::Error
    -这并不总是微不足道的。例如,我如何映射
    TooManyRedirects
    ?我可以使用std::io::ErrorKind::Other,但感觉不对

  • 定义我自己的错误类型
    MyError
    并为
    reqwest::error
    MyError
    MyError
    std::io::error
    实现
    std::convert::From
    -这引发了以前的同样问题-并非所有错误都可以轻易转换


  • 还有其他更好的选择吗

    使用
    io::Error
    是唯一可以做的事情,因为这是trait所需要的契约。其他一切都归结为细节和人体工程学

    接受可转换为
    error::error
    的和

    我可能会编写一个函数,通过调用
    io::error::new
    将域错误转换为
    io::error
    ,然后在
    map\u err
    中随处使用这个新函数。我会先把所有的东西塞进
    ErrorKind::Other
    ,直到我找到了一个特定的Reqwest错误应该是其他错误的原因

    你的消费者真的会在意太多的重定向吗?通过构造,答案必须是“否”,因为它们可能在
    文件
    TcpSocket
    上操作,这两个文件都没有这样的概念

    我不相信我会在这种情况下创建包装错误类型;我看不出它有什么价值。它需要额外的类型注释,您可以通过函数“免费”获得这些注释

    这并不总是微不足道的

    这是正确的-将两个完全不同的部分粘在一起有时并不能完全按照我们想要的方式排列。这就是为什么编程既令人兴奋又糟糕的部分原因