Crates.io | enum-code |
lib.rs | enum-code |
version | 0.1.1 |
source | src |
created_at | 2023-06-14 03:31:45.645011 |
updated_at | 2023-06-14 03:46:13.214334 |
description | derive(Code) simplifies error handling by providing an easy-to-use enumeration of error codes |
homepage | https://github.com/Kunduin/enum-code |
repository | https://github.com/Kunduin/enum-code |
max_upload_size | |
id | 889712 |
size | 8,362 |
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.
enum-code
is published on Cargo and can be installed using:
$ cargo add enum-code
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,
}
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,
}
}
}
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」
MIT