err-derive 0.1.3

Derive macro for `std::error::Error`
Documentation

err-derive

A failure-like derive macro for the std Error. The source code mostly copied from failure-derive.

Motivation

Why yet another error handling library? There already are dozen others, the most popular being:

The former provides a nice #[derive(Fail)] macro, but it uses its own error type (Fail) and its usage is rather discouraged since std::error::Error is getting fixed to provide the same benefits as Fail.

error-chain does support std::error::Error, but it uses a declarative for generating the error implementation which makes the syntax too obscure in my opinion.

This crate tries to combine both advantages:

  • work with std::error::Error
  • provide a custom #[derive(Error)] that works just like failure-derive

err-derive is compatible with std, including the recent change to deprecate Error::cause in favour of Error::source, and provides an easy syntax for generating the Display and Error boilerplate (the latter being 99% copied from failure-derive).

Features

err-derive can be applied to your error struct / enum and does the following for you:

  • Derive Display implementation
  • Derive Error implementation (implementing source to return the cause of the error)

Planned features

  • Derive From<OtherError> implementations

Usage

Cargo.toml:

[dependencies]
err-derive = "0.1"

Rust code:

#[macro_use]
extern crate err_derive;

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(cause)] io_error: io::Error,
}

/// `MyEnumError::source` will return a reference only if it is `Variant2`,
/// otherwise it will return `None`.
#[derive(Debug, Error)]
enum MyEnumError {
    #[error(display = "An error occurred.")]
    Variant1,
    #[error(display = "A different error occurred.")]
    Variant2(#[error(cause)] io::Error),
}

Credit

Credit goes to @withoutboats and other contributors of failure.

License

This project is dual-licensed under Apache-2.0 / MIT. You're free to choose one of both licenses. Every contribution made to this project is assumed to be licensed according to these terms.

See LICENSE, LICENSE-MIT and LICENSE-APACHE for more information.