cdumay_error_derive 1.0.1

Streamlining Error Handling in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! [![License: BSD-3-Clause](https://img.shields.io/badge/license-BSD--3--Clause-blue)](./LICENSE)
//! [![cdumay_error_derive on crates.io](https://img.shields.io/crates/v/cdumay_error_derive)](https://crates.io/crates/cdumay_error_derive)
//! [![cdumay_error_derive on docs.rs](https://docs.rs/cdumay_error_derive/badge.svg)](https://docs.rs/cdumay_error_derive)
//! [![Source Code Repository](https://img.shields.io/badge/Code-On%20GitHub-blue?logo=GitHub)](https://github.com/cdumay/cdumay_error_derive)
//!
//! The `cdumay_error_derive` crate provides procedural macros to simplify the creation of custom error types in Rust. By leveraging these macros,
//! developers can efficiently define error structures that integrate seamlessly with the `cdumay_error` error management ecosystem.
//!
//! # Overview
//!
//! Error handling in Rust often involves creating complex structs to represent various error kinds and implementing traits to provide context and
//! conversions. The `cdumay_error_derive` crate automates this process by offering macros that generate the necessary boilerplate code, allowing for
//! more readable and maintainable error definitions.
//!
//! # Features
//!
//! * **Macros**: Automatically generate implementations for custom error types.
//! * **Integration with cdumay_error**: Designed to work cohesively with the `cdumay_error` crate, ensuring consistent error handling patterns.
//!
//! # Usage
//!
//! To utilize `cdumay_error_derive` in your project, follow these steps:
//!
//! 1. **Add Dependencies**: Include `cdumay_error` with the feature `derive` in your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! cdumay_error = { version = "1.0", features = ["derive"] }
//! ```
//!
//! 2. **Define Error**: Use the provided derive macros to define your error and error kind structs:
//!
//! ```rust
//! use cdumay_error::{define_errors, define_kinds, AsError};
//!
//! define_kinds! {
//!     UnknownError = ("Err-00001", 500, "Unexpected error"),
//!     IoError = ("Err-00001", 400, "IO error")
//! }
//! define_errors! {
//!     Unexpected = UnknownError,
//!     FileRead = IoError,
//!     FileNotExists = IoError
//! }
//! ```
//! In this example:
//!
//! * define_kinds create `cdumay_error::ErrorKind` structs representing different categories of errors.
//! * define_errors create `cdumay_error::Error` struct that contains an ErrorKind and metadata.
//!
//! 3. **Implementing Error Handling**: With the above definitions, you can now handle errors in your application as follows:
//!
//! ```rust
//! use std::fs::File;
//! use std::io::Read;
//! use cdumay_error::{define_errors, define_kinds, AsError};
//!
//! define_kinds! {
//!     UnknownError = ("Err-00001", 500, "Unexpected error"),
//!     IoError = ("Err-00001", 400, "IO error")
//! }
//! define_errors! {
//!     Unexpected = UnknownError,
//!     FileRead = IoError,
//!     FileNotExists = IoError
//! }
//!
//! fn try_open_file(path: &str) -> cdumay_error::Result<String> {
//!     let mut file = File::open(path).map_err(|err| FileNotExists::new().set_message(err.to_string()))?;
//!     let mut content = String::new();
//!     file.read_to_string(&mut content).map_err(|err| FileRead::new().set_message(err.to_string()))?;
//!     Ok(content)
//! }
//!
//! fn main() {
//!     let path = "example.txt";
//!
//!     match try_open_file(path) {
//!         Ok(content) => println!("File content:\n{}", content),
//!         Err(e) => eprintln!("{}", e),
//!     }
//! }
//! ```
//! This will output:
//!
//! ```text
//! [Err-00001] Client::IoError::FileNotExists (400) - No such file or directory (os error 2)
//! ```
extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::{parenthesized, parse_macro_input, Ident, LitInt, LitStr, Token, Type};

struct ErrorKindArgs {
    const_name: Ident,
    _eq: Token![=],
    _parens: syn::token::Paren,
    message: LitStr,
    _comma1: Token![,],
    code: LitInt,
    _comma2: Token![,],
    description: LitStr,
}

impl Parse for ErrorKindArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let const_name: Ident = input.parse()?;
        let _eq: Token![=] = input.parse()?;

        let content;
        let _parens = parenthesized!(content in input);

        let message: LitStr = content.parse()?;
        let _comma1: Token![,] = content.parse()?;
        let code: LitInt = content.parse()?;
        let _comma2: Token![,] = content.parse()?;
        let description: LitStr = content.parse()?;

        Ok(ErrorKindArgs {
            const_name,
            _eq,
            _parens,
            message,
            _comma1,
            code,
            _comma2,
            description,
        })
    }
}

struct ErrorKindArgsList {
    items: Punctuated<ErrorKindArgs, Comma>,
}

impl Parse for ErrorKindArgsList {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(ErrorKindArgsList {
            items: Punctuated::parse_terminated(input)?,
        })
    }
}

/// The `define_kinds` macro is a procedural macro that generates constants of type `cdumay_error::ErrorKind`. This macro simplifies the definition
/// of structured error kinds by allowing developers to declare them using a concise syntax. It takes a list of error definitions and expands
/// them into properly structured `cdumay_error::ErrorKind` constants.
///
/// # Usage Example
///
/// ## Macro Input
///
/// ```rust
/// use cdumay_error::{define_errors, define_kinds, AsError};
///
/// define_kinds! {
///     FileNotFound = ("File not found", 404, "The requested file could not be located"),
///     PermissionDenied = ("Permission denied", 403, "The user lacks the necessary permissions")
/// }
/// ```
/// ## Macro Expansion (Generated Code)
///
/// ```rust
/// #[allow(non_upper_case_globals)]
/// pub const FileNotFound: cdumay_error::ErrorKind = cdumay_error::ErrorKind(
///     "FileNotFound",
///     "File not found",
///     404,
///     "The requested file could not be located"
/// );
///
/// #[allow(non_upper_case_globals)]
/// pub const PermissionDenied: cdumay_error::ErrorKind = cdumay_error::ErrorKind(
///     "PermissionDenied",
///     "Permission denied",
///     403,
///     "The user lacks the necessary permissions"
/// );
/// ```
#[proc_macro]
pub fn define_kinds(input: TokenStream) -> TokenStream {
    let args_list = parse_macro_input!(input as ErrorKindArgsList);

    let constants = args_list.items.iter().map(|args| {
        let const_name = &args.const_name;
        let message = &args.message;
        let code = &args.code;
        let description = &args.description;

        quote! {
            #[allow(non_upper_case_globals)]
            pub const #const_name: cdumay_error::ErrorKind = cdumay_error::ErrorKind(stringify!(#const_name), #message, #code, #description);
        }
    });

    TokenStream::from(quote! {
        #(#constants)*
    })
}

struct ErrorDefinition {
    name: Ident,
    kind: Type,
}

struct ErrorDefinitions {
    definitions: Vec<ErrorDefinition>,
}

impl Parse for ErrorDefinitions {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut definitions = Vec::new();

        while !input.is_empty() {
            let name: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            let kind: Type = input.parse()?;
            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
            definitions.push(ErrorDefinition { name, kind });
        }

        Ok(ErrorDefinitions { definitions })
    }
}

/// The `define_errors` macro is a procedural macro that generates structured error types implementing `cdumay_error::AsError`. This macro simplifies
/// error handling by defining error structures with relevant metadata, serialization, and error conversion logic.
///
/// Each generated struct:
///
/// * Implements `cdumay_error::AsError` for interoperability with `cdumay_error::ErrorKind`.
/// * Provides methods for setting error messages and details.
/// * Supports conversion from `cdumay_error::Error`.

/// # Usage Example
///
/// ## Macro Input
///
/// ```rust
/// use cdumay_error::{define_errors, define_kinds, AsError};
///
/// define_kinds! {
///     FileNotFound = ("File not found", 404, "The requested file could not be located"),
///     PermissionDenied = ("Permission denied", 403, "The user lacks the necessary permissions")
/// }
///
/// define_errors! {
///     NotFoundError = FileNotFound,
///     UnauthorizedError = PermissionDenied
/// }
/// ```
/// ## Macro Expansion (Generated Code for NotFoundError)
///
/// ```rust
/// use cdumay_error::{define_errors, define_kinds, AsError};
///
/// define_kinds! {
///     FileNotFound = ("File not found", 404, "The requested file could not be located")
/// }
///
/// #[derive(Debug, Clone)]
/// pub struct NotFoundError {
///     class: String,
///     message: String,
///     details: Option<std::collections::BTreeMap<String, serde_value::Value>>,
/// }
///
/// impl NotFoundError {
///     pub const kind: cdumay_error::ErrorKind = FileNotFound;
///
///     pub fn new() -> Self {
///         Self {
///             class: format!("{}::{}::{}", Self::kind.side(), Self::kind.name(), "NotFoundError"),
///             message: Self::kind.description().into(),
///             details: None,
///         }
///     }
///
///     pub fn set_message(mut self, message: String) -> Self {
///         self.message = message;
///         self
///     }
///
///     pub fn set_details(mut self, details: std::collections::BTreeMap<String, serde_value::Value>) -> Self {
///         self.details = Some(details);
///         self
///     }
///
///     pub fn convert(error: cdumay_error::Error) -> Self {
///         let mut err_clone = error.clone();
///         let mut details = error.details.unwrap_or_default();
///         err_clone.details = None;
///         details.insert("origin".to_string(), serde_value::to_value(err_clone).unwrap());
///
///         Self {
///             class: format!("{}::{}::{}", Self::kind.side(), Self::kind.name(), "NotFoundError"),
///             message: Self::kind.description().into(),
///             details: Some(details),
///         }
///     }
/// }
///
/// impl cdumay_error::AsError for NotFoundError {
///     fn kind() -> cdumay_error::ErrorKind {
///         Self::kind
///     }
///     fn class(&self) -> String {
///         self.class.clone()
///     }
///     fn message(&self) -> String {
///         self.message.clone()
///     }
///     fn details(&self) -> Option<std::collections::BTreeMap<String, serde_value::Value>> {
///         self.details.clone()
///     }
/// }
///
/// impl std::error::Error for NotFoundError {}
///
/// impl std::fmt::Display for NotFoundError {
///     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
///         write!(f, "[{}] {} ({}): {}", Self::kind.message_id(), "NotFoundError", Self::kind.code(), self.message())
///     }
/// }
/// ```
#[proc_macro]
pub fn define_errors(input: TokenStream) -> TokenStream {
    let definitions = parse_macro_input!(input as ErrorDefinitions);

    let generated_structs = definitions.definitions.iter().map(|definition| {
        let name = &definition.name;
        let kind = &definition.kind;

        quote! {
            #[derive(Debug, Clone)]
            pub struct #name {
                class: String,
                message: String,
                details: Option<std::collections::BTreeMap<String, serde_value::Value>>,
            }

            impl #name {
                pub const kind: cdumay_error::ErrorKind = #kind;
                pub fn new() -> Self {
                    Self {
                        class: format!("{}::{}::{}", Self::kind.side(), Self::kind.name(), stringify!(#name)),
                        message: Self::kind.description().into(),
                        details: None,
                    }
                }
                pub fn set_message(mut self, message: String) -> Self {
                    self.message = message;
                    self
                }
                pub fn set_details(mut self, details: std::collections::BTreeMap<String, serde_value::Value>) -> Self {
                    self.details = Some(details);
                    self
                }
                pub fn convert(error: cdumay_error::Error) -> Self {
                    let mut err_clone = error.clone();
                    let mut details = error.details.unwrap_or_default();
                    err_clone.details = None;
                    details.insert("origin".to_string(), serde_value::to_value(err_clone).unwrap());
                    Self {
                        class: format!("{}::{}::{}", Self::kind.side(), Self::kind.name(), stringify!(#name)),
                        message: Self::kind.description().into(),
                        details: Some(details),
                    }
                }
            }
            impl cdumay_error::AsError for #name {
                fn kind()-> cdumay_error::ErrorKind {
                    Self::kind
                }
                fn class(&self) -> String {
                    self.class.clone()
                }
                fn message(&self) -> String {
                    self.message.clone()
                }
                fn details(&self) -> Option<std::collections::BTreeMap<String, serde_value::Value>> {
                    self.details.clone()
                }
            }

            impl std::error::Error for #name {}

            impl std::fmt::Display for #name {
                fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                    write!(f, "[{}] {} ({}): {}", Self::kind.message_id(), stringify!(#name), Self::kind.code(), self.message())
                }
            }
        }
    });

    TokenStream::from(quote! {
        #(#generated_structs)*
    })
}