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
use std::fmt;
use std::fs::OpenOptions;
use std::io::prelude::*;

///an alias for result that uses dynamic errors
pub type DynResult<T> = std::result::Result<T, Box<dyn std::error::Error>>;

/// a macro for returning custom errors as dynamic errors
/// 
/// #Example
/// ```ignore
/// if x > 3 {dynerr!(MyError::CustomError("x less than 3"))}
/// ```
#[macro_export]
macro_rules! dynerr {
    ($e:expr) => {return Err(Box::new($e))};
}

/// performs a dynamic match operation on multiple error types\
/// takes the DynError, match arms, and default arm\
/// types must be specified beforehand with the "type" keyword
/// 
/// #Example
/// ```ignore
/// ...
/// let i = match example(9) { //returns dyn error
///     Ok(i) => i,
///     Err(e) => {
///         dynmatch!(e,                                                    //the error to match
///             type ExampleError1 {                                        //error type group
///                 arm ExampleError1::ThisError(2) => panic!("it was 2!"), //arm [pattern] => {code}
///                 _ => panic!("{}",e)                                     //_ => {code}
///             },
///             type ExampleError2 {                                        //another error type
///                 arm ExampleError2::ThatError(8) => panic!("it was 8!"), //more arms
///                 arm ExampleError2::ThatError(9) => 9,
///                 _ => panic!("{}",e)                                     //more wildcard matches
///             }, 
///             _ => panic!("{}",e)                                         //final wildcard if type not found
///         )
///     }
/// };
/// ...
/// ```
#[macro_export]
macro_rules! dynmatch {
    ($e:expr, $(type $ty:ty {$(arm $pat:pat => $result:expr),*, _ => $any:expr}),*, _ => $end:expr) => (
        $(
            if let Some(e) = $e.downcast_ref::<$ty>() {
                match e {
                    $(
                        $pat => {$result}
                    )*
                    _ => $any
                }
            } else
        )*
        {$end}
    );
}

/// appends [event] to [log_file]\
/// creates file if it doesnt exist\
/// panics on failure to create or appending to file
pub fn log<T: fmt::Display>(event: T, log_file: &str) -> T {
    let mut file = OpenOptions::new()
        .append(true)
        .create(true)
        .open(log_file)
        .unwrap_or_else(|e| panic!("Dynerr: Error opening log during crash: {} (error passed to logger was: {})",e,event));
    file.write_all(format!("{}\n",event.to_string()).as_bytes())
        .unwrap_or_else(|e| panic!("Dynerr: Error appending to log during crash: {} (error passed to logger was: {})",e,event));
    event
}

/// logs message to file\
/// if no file supplied then defaults to "event.log"
/// 
/// #Example
/// ```ignore
/// example(9).unwrap_or_else(|e|log!(e), "error.log")
/// log!("i just logged an error to error.log!")
/// ```
#[macro_export]
macro_rules! log {
    ($event:expr) => {
        $crate::log($event, "event.log")
    };
    ($event:expr, $log:expr) => {
        $crate::log($event, $log)
    };
}

/// logs error to file then panic!\
/// if no file supplied then defaults to "event.log"
/// 
/// #Example
/// ```ignore
/// example(9).unwrap_or_else(|e|logged_panic!(e));
/// example(9).unwrap_or_else(|e|logged_panic!(e), "mylog.log");
/// ```
#[macro_export]
macro_rules! logged_panic {
    ($e: expr) => {
        panic!("{}",log!($e));
    };

    ($e: expr, $log:expr) => {
        panic!("{}",log!($e, $log));
    }
}


/// Does .unwrap_or_else(|e| logged_panic!(e)) on result\
/// if no file supplied then defaults to "event.log"
/// 
/// #Example
/// ```ignore
/// let _i = check!(example(9);
/// check!(example(9, "error.log");
/// ```
#[macro_export]
macro_rules! check {
    ($x:expr) => {
        $x.unwrap_or_else(|e| logged_panic!(e))
    };
    ($x:expr, $log:expr) => {
        $x.unwrap_or_else(|e| logged_panic!(e, $log))
    };
}


///just some tests
#[cfg(test)]
mod tests {
    use super::*;
    //THIS SECTION IS CREATING THE FIRST CUSTOM ERROR
    use std::{fmt, error};
    ///a custom error type
    #[derive(Debug)]
    enum ExampleError1 {
        ThisError(u32),
    }
    //impl display formatting for error
    impl fmt::Display for ExampleError1 {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match self {
                ExampleError1::ThisError(i)      => write!(f, "ExampleError1::ThisError: {}",i),
            }
        }
    }
    //impl error conversion for error
    impl error::Error for ExampleError1 {}

    //THIS SECTION IS CREATING THE SECOND CUSTOM ERROR
    #[derive(Debug)]
    enum ExampleError2 {
        ThatError(u32),
    }
    impl fmt::Display for ExampleError2 {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match self {
                ExampleError2::ThatError(i)      => write!(f, "ExampleError2::ThatError: {}",i),
            }
        }
    }
    impl error::Error for ExampleError2 {}

    ///THIS SECTION IS USING IT
    #[test]
    pub fn test() -> DynResult<()> {    
        ///shows error handling capabilities using DynError
        fn example(x: u32) -> DynResult<u32> {
            match x {
                1      => Ok(x),                                //Ok
                2..=4  => dynerr!(ExampleError1::ThisError(x)), //custom error
                5..=10 => dynerr!(ExampleError2::ThatError(x)), //different custom error
                _      => {     
                    std::env::current_dir()?;                   //an error not even defined by you!
                    Ok(x)
                }
            }
        }

        log!("this is a test", "test.log");
        let _i = match example(2) {
            Ok(i) => i,
            Err(e) => {
                dynmatch!(e,                                                            //the dynamic error to be matched
                    type ExampleError1 {                                                //an error group
                        arm ExampleError1::ThisError(2) => logged_panic!("it was 2!"),  //arm [pattern] => {code}
                        _ => panic!("{}",e)                                             //_ => {code}
                    },
                    type ExampleError2 {
                        arm ExampleError2::ThatError(8) => logged_panic!("it was 8!", "test.log"),
                        arm ExampleError2::ThatError(9) => 9,
                        _ => panic!("{}",e)
                    }, 
                    _ => panic!("{}",e)                                                 //what to do if error group isn't found
                )
            }
        };
        log!("do logged_panic! if error");
        let _i = check!(example(11));
        let _i = check!(example(9), "test.log");
        Ok(())
    }
}