Crate derive_error_kind

Crate derive_error_kind 

Source
Expand description

§derive-error-kind

A Rust procedural macro for implementing the ErrorKind pattern that simplifies error classification and handling in complex applications.

§Motivation

The ErrorKind pattern is a common technique in Rust for separating:

  • The kind of an error (represented by a simple enum)
  • The details of the error (contained in the error structure)

This allows developers to handle errors more granularly without losing context.

Rust’s standard library uses this pattern in std::io::ErrorKind, and many other libraries have adopted it due to its flexibility. However, manually implementing this pattern can be repetitive and error-prone, especially in applications with multiple nested error types.

This crate solves this problem by providing a derive macro that automates the implementation of the ErrorKind pattern.

§Overview

The ErrorKind macro allows you to associate error types with a specific kind from an enum. This creates a clean and consistent way to categorize errors in your application, enabling more precise error handling.

Key features:

  • Automatically implements a .kind() method that returns a categorized error type
  • Supports nested error types via the transparent attribute
  • Works with unit variants, named fields, and tuple variants
  • Enables transparent error propagation through error hierarchies

§Basic Usage

First, define an enum for your error kinds:

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ErrorKind {
    NotFound,
    InvalidInput,
    InternalError,
}

Then, use the ErrorKind derive macro on your error enums:

use derive_error_kind::ErrorKind;

#[derive(Debug, ErrorKind)]
#[error_kind(ErrorKind)]
pub enum MyError {
    #[error_kind(ErrorKind, NotFound)]
    ResourceNotFound,

    #[error_kind(ErrorKind, InvalidInput)]
    BadRequest { details: String },

    #[error_kind(ErrorKind, InternalError)]
    ServerError(String),
}

// Now you can use the .kind() method
let error = MyError::ResourceNotFound;
assert_eq!(error.kind(), ErrorKind::NotFound);

§Attribute Reference

  • #[error_kind(KindEnum)]: Top-level attribute that specifies which enum to use for error kinds
  • #[error_kind(KindEnum, Variant)]: Variant-level attribute that specifies which variant of the kind enum to return
  • #[error_kind(transparent)]: Variant-level attribute for nested errors, indicating that the inner error’s kind should be used

§Requirements

  • The macro can only be applied to enums
  • Each variant must have an error_kind attribute
  • The kind enum must be in scope and accessible

Derive Macros§

ErrorKind
Create a kind method for struct