如何为所有现有错误实现错误包装?

时间:2015-04-30 04:05:33

标签: 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`

1 个答案:

答案 0 :(得分:7)

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

  • 为您的类型实施the Error trait
  • 为要与std::convert::From运算符无缝使用的错误类型实施?quick_error包可帮助自动执行此操作。)