rust - 如何实现一个现有错误类型的错误包装器?

标签 rust

我想在所有函数中使用我的自定义错误类型,并且需要包装现有的标准错误,以便?运算符成功。

这是我在做什么:

use std::{error::Error, fmt, fs};

#[derive(Debug)]
enum MyError {
    A,
    B,
}

impl fmt::Display for MyError {
    fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
        Ok(())
    }
}

impl Error for MyError {
    fn description(&self) -> &str {
        ""
    }
}

trait NotMyError {}

impl<T: NotMyError + Error> From<T> for MyError {
    fn from(_: T) -> MyError {
        MyError::A
    }
}

fn test() -> Result<(), MyError> {
    fs::read_dir("test")?;
    Ok(())
}

fn main() {}

编译器抱怨:

error[E0277]: the trait bound `std::io::Error: NotMyError` is not satisfied
  --> src/main.rs:30:5
   |
30 |     fs::read_dir("test")?;
   |     ^^^^^^^^^^^^^^^^^^^^^ the trait `NotMyError` is not implemented for `std::io::Error`
   |
   = note: required because of the requirements on the impl of `std::convert::From<std::io::Error>` for `MyError`
   = note: required by `std::convert::From::from`

最佳答案

an excellent post about it。要获得错误的一流支持,您需要做两件事:

  • 为您的类型实现the Error trait
  • 为想要与std::convert::From运算符无缝使用的错误类型实现?(quick_error crate 可自动执行此操作)。
  • 关于rust - 如何实现一个现有错误类型的错误包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29958807/

    相关文章:

    rust - 无法调用 fn<T : X> from an impl<T: X> because X is not satisfied for T

    rust - Rust SDL : how do I “attach” a surface to a window?

    unit-testing - 如何在 Rust 中运行任何测试之前运行设置代码?

    rust - 仅将功能导出到模块测试?

    rust - 使用 Box 分配大型数组时,线程 '<main>' 已溢出其堆栈

    rust - reqwest : Unable to deserialize JSON response + `match` issues 出现问题

    closures - 有什么办法可以显式地写出闭包的类型吗?

    python-3.x - pip install fastapi [all]由于 rust 组件而失败?

    rust - 如何返回 Arc<Vec<u8>> 作为 super 响应?

    rust - 如果不允许同时使用两个可变引用,那为什么还要允许它们呢?