#derive #error #display

macro derive-enum-error

Derive macro for std::error::Error

1 unstable release

0.0.1 Jul 4, 2019

#66 in #display

Download history 29/week @ 2021-10-04 46/week @ 2021-10-11 210/week @ 2021-10-18 91/week @ 2021-10-25 100/week @ 2021-11-01 65/week @ 2021-11-08 112/week @ 2021-11-15 51/week @ 2021-11-22 86/week @ 2021-11-29 36/week @ 2021-12-06 63/week @ 2021-12-13 30/week @ 2021-12-20 7/week @ 2021-12-27 43/week @ 2022-01-03 126/week @ 2022-01-10 92/week @ 2022-01-17

268 downloads per month

MIT/Apache

10KB
171 lines

derive_enum_error

Crates.io API Docs

A failure-like derive macro for the std::error::Error. The source code is mostly copied from failure_derive & err-derive.

Compare with err-derive

  • Only support enum type error
  • Auto impl From<T> for error
  • Support edition = "2018"
  • Rust version requires >= 1.30.0
  • Use source keyword instead of cause
  • Use call_site for more debug information

lib.rs:

derive_enum_error

Deriving error sources

Add an #[error(source)] attribute to the field:

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,
}
#
# fn main() {}

Formatting fields

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 },
}
#
# fn main() {}

Printing the error

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();
    }
}

Dependencies

~2MB
~43K SLoC