enum-code 0.1.1

derive(Code) simplifies error handling by providing an easy-to-use enumeration of error codes
Documentation
  • Coverage
  • 50%
    1 out of 2 items documented1 out of 2 items with examples
  • Size
  • Source code size: 8.97 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 280.14 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 4s Average build duration of successful builds.
  • all releases: 4s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • Kunduin/enum-code
    6 1 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • Kunduin

enum-code

Introduction

enum-code is a derive macro for enum types. This library generates code that associates error codes with error types. It can be used in conjunction with the thiserror crate. Developers can quickly retrieve error codes by calling the get_code method.

Installation

enum-code is published on Cargo and can be installed using:

$ cargo add enum-code

Usage

  1. Add the Code attribute to the enum type:

    #[derive(enum_code::Code)]
    enum TestError {
        #[code(1)]
        Tuple(String),
        #[code(2)]
        Struct { message: String },
        #[code(3)]
        Simple,
    }
    
  2. Code Generation

    For the TestError enum above, an associated impl TestError struct is generated, which includes a get_code method that returns the corresponding error code based on the variant value.

    impl TestError {
        pub const fn get_code(&self) -> u32 {
            match self {
                TestError::Tuple(..) => 1u32,
                TestError::Struct { .. } => 2u32,
                TestError::Simple => 3u32,
            }
        }
    }
    
  3. Retrieving Error Codes

    Error codes can be retrieved by calling get_code:

    let err = TestError::Tuple("error message".to_owned());
    let code = err.get_code();
    println!("error code: {}", code); // should print 「error code: 1」
    

LICENSE

MIT