1 个不稳定版本
| 0.0.1 | 2019年7月4日 | 
|---|
#28 在 #derive-error
11KB
171 行
derive_enum_error
一个类似于失败(failure)的派生宏,用于 std::error::Error。源代码主要来自 failure_derive 和 err-derive。
与 err-derive 进行比较
- 仅支持枚举类型错误
- 自动实现错误类型 From<T>
- 支持 edition = "2018"
- Rust版本要求 >= 1.30.0
- 使用 source关键字代替cause
- 使用 call_site获取更多调试信息
lib.rs:
derive_enum_error
派生错误源
将 #[error(source)] 属性添加到字段
use derive_enum_error::Error;
use std::io;
/// `MyError::source` will return a reference to the `io_error` field
#[derive(Debug, Error)]
#[error(display = "An error occurred.")]
struct MyError {
    #[error(source)]
    io_error: io::Error,
}
#
字段格式化
use derive_enum_error::Error;
use std::path::PathBuf;
#[derive(Debug, Error)]
pub enum FormatError {
    #[error(display = "invalid header (expected: {:?}, got: {:?})", expected, found)]
    InvalidHeader {
        expected: String,
        found: String,
    },
    // Note that tuple fields need to be prefixed with `_`
    #[error(display = "missing attribute: {:?}", _0)]
    MissingAttribute(String),
}
#[derive(Debug, Error)]
pub enum LoadingError {
    #[error(display = "could not decode file")]
    FormatError(#[error(source)] FormatError),
    #[error(display = "could not find file: {:?}", path)]
    NotFound { path: PathBuf },
}
#
打印错误
use std::error::Error;
fn print_error(e: &dyn Error) {
    eprintln!("error: {}", e);
    let mut source = e.source();
    while let Some(e) = source {
        eprintln!("sourced by: {}", e);
        source = e.source();
    }
}
依赖项
~2MB
~48K SLoC