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
/// Defining an error with set of reason.
/// # Usage
/// ```
/// use error_ex::{create_error};
/// create_error!(ErrorType => ErrorReason1, ErrorReason2, ErrorReason3);
/// ```
/// ## Examples
///
/// ```
/// use error_ex::{create_error};
///
/// create_error!(InputError => IllegalArgument, InvalidInput, MissingArgument);
/// //Now, you can use the following code to instantiate this error
/// InputError::illegal_argument(format!("Your message here"));
///
/// ```
///
/// ## Error Mapping
///
/// The explicit way
/// ```
/// use std::fs;
/// use error_ex::{create_error};
///
/// create_error!(FileError => IoError);
/// create_error!(SchemaError => ParseError);
///
/// let error: Result<(), FileError> = Err(FileError::io_error("".to_string()));
///
/// let mapped = error.map_err(|error| {
///     SchemaError::parse_error(format!("SchemaError::ParseError error {error}"))
/// });
///
/// ```
/// ## Function wrapper
/// The above code can be simplified using `map_to__error!`
/// macro using the build in lower order function
/// ```
///
/// use std::fs;
/// use std::io::Error;
/// use error_ex::{create_error};
///
/// create_error!(FileError => IoError);
/// create_error!(SchemaError => ParseError);
///
/// let error: Result<(), FileError> = Err(FileError::io_error("".to_string()));
///
/// let mapped = error.map_err(SchemaError::map_to_parse_error);
///
/// ```
///
#[macro_export]
macro_rules! create_error {
    ( $error:ident => $( $error_reason:ident ),* ) => {
        paste::paste! {

            #[derive(Debug, Clone, PartialEq, Eq)]
            pub struct $error {
                pub reason: [<$error Reason>],
                pub message: String,
            }

            #[derive(Debug, Clone, PartialEq, Eq)]
            #[allow(unused_qualifications)]
            pub enum [<$error Reason>] {
                $(
                    [<$error_reason>],
                )*
            }

            impl $error {
                $(
                    #[allow(unused_qualifications)]
                    pub fn [<$error_reason:snake>](message: String) -> $error {
                        $error {
                            reason: [<$error Reason>]::$error_reason,
                            message,
                        }
                    }
                )*

                $(
                    #[allow(unused_qualifications)]
                    pub fn [<map_to_ $error_reason:snake>]<E>(error: E) -> $error
                    where
                        E: std::error::Error,
                    {
                        let error_name = stringify!($error);
                        let error_reason_name = stringify!($error_reason);
                        let error_string =
                            format!("{}::{} caused by {}", error_name, error_reason_name, error);
                        $error {
                            reason: [<$error Reason>]::$error_reason,
                            message: error_string,
                        }
                    }
                )*
            }


            impl std::error::Error for $error {}

            impl std::fmt::Display for $error {
                fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                    let error_name = stringify!([<$error:camel>]);
                    write!(
                        f,
                        "{:#?} error, reason: {:#?}, message {:#?}",
                        error_name,
                        self.reason,
                        self.message
                    )
                }
            }
        }
    };
}