#error #derive-error #display #derive

errorderive

std::error::Error 提供的派生宏

1 个不稳定版本

0.0.1 2019年7月4日

#27#derive-error

MIT/Apache

11KB
171

errorderive

Crates.io API Docs

std::error::Error 提供类似失败的派生宏。源代码大部分来自 failure_derive & err-derive

与 err-derive 进行比较

  • 支持 edition = "2018"
  • Rust 版本要求 >= 1.30.0
  • 使用 source 关键字代替 cause
  • 使用 call_site 获取更多调试信息

lib.rs:

errorderive

派生错误源

#[error(source)] 属性添加到字段

use errorderive::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 errorderive::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