[][src]Crate err_derive

err-derive

Deriving error causes / sources

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

use std::io;
use err_derive::Error;

/// `MyError::source` will return a reference to the `io_error` field
#[derive(Debug, Error)]
#[error(display = "An error occurred.")]
struct MyError {
    #[error(cause)]
    io_error: io::Error,
}

Formatting fields

use std::path::PathBuf;
use err_derive::Error;

#[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(cause)] FormatError),
    #[error(display = "could not find file: {:?}", path)]
    NotFound { path: PathBuf },
}

Printing the error

use std::error::Error;

fn print_error(e: &dyn Error) {
    eprintln!("error: {}", e);
    let mut cause = e.source();
    while let Some(e) = cause {
        eprintln!("caused by: {}", e);
        cause = e.source();
    }
}

Derive Macros

Error