#error #derive


Derive macro for Error using macros 1.1

6 releases

Uses old Rust 2015

0.0.5 Feb 26, 2021
0.0.4 Oct 4, 2017
0.0.3 Jan 29, 2017

#904 in Rust patterns

Download history 4301/week @ 2021-08-10 4774/week @ 2021-08-17 4704/week @ 2021-08-24 4557/week @ 2021-08-31 6066/week @ 2021-09-07 7484/week @ 2021-09-14 10804/week @ 2021-09-21 6975/week @ 2021-09-28 3965/week @ 2021-10-05 4017/week @ 2021-10-12 4040/week @ 2021-10-19 6658/week @ 2021-10-26 4712/week @ 2021-11-02 3198/week @ 2021-11-09 3657/week @ 2021-11-16 3875/week @ 2021-11-23

16,800 downloads per month
Used in less than 28 crates


311 lines

Derive Rust Errors

Build Status Latest Version Docs

This crate uses macros 1.1 to derive custom errors.

Getting Started

Add this crate to your dependencies section:-

derive-error = "0.0.4"

Import it in your main.rs or lib.rs:-

extern crate derive_error;

Deriving errors is simple. Simply create an enum for your errors as suggested in the Rust book, add short descriptions for the enum variants using doc comments, throw in a #[derive(Debug, Error)] and you are done. Here is the example in the book implemented using this library:-

#[derive(Debug, Error)]
enum CliError {
  /// IO Error
  /// Failed to parse the CSV file
  /// No matching cities with a population were found

This will derive implementations for Display, Error and From. See the reql crate for a real world example of how to use this crate.


Not all errors are exactly the same and need, for example, From implementations. derive-error supports attributes on Enum variants that allow you to enable/disable certain aspects of how Error deriving functions. There are 3 attributes that can be attached to variants of enums deriving Error: non_std, msg_embedded, no_from.

msg_embedded displays the error through an item in the variant, generally a String.

no_from skips the From impl for the variant of the enum, you want this if the error isn't coming from somewhere else, and your code is essentially the source of the error.

non_std displays the error from the variant via it's doc comment /// or it's embedded message (if the variant has that attribute), otherwise it will try and use the cause of the underlying error inside the variant. This is usually combined with no_from.

#[derive(Debug, Error)]
enum Error {
	#[error(msg_embedded, no_from, non_std)]


	#[error(non_std, no_from)]

This example showcases how to attach the attributes. RuntimeError has a String internally which in the case of an error will be used for displaying. Io is getting a From implementation for Io::Error and this is generally the most common usecase. It is also possible to embed values directly in errors, in the Json variant it's embedding a Value inside, to be used later on for other information.

These were adapted from the the reql crate's usage of derive-error


~38K SLoC