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
use std::error::Error;
use std::fmt;

/// The `Result` type for this library.
pub type Result<T> = std::result::Result<T, XErr>;

/// A generic error type for this library.
#[derive(Debug)]
pub struct XErr {
    /// The error message.
    pub message: String,
    /// The sourcecode file where the error was raised.
    pub file: String,
    /// The sourcecode line where the error was raised.
    pub line: u64,
    /// The underlying error that is being wrapped.
    pub source: Option<Box<dyn Error>>,
}

impl fmt::Display for XErr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(src) = &self.source {
            write!(
                f,
                "{}:{} {}: {}",
                self.file,
                self.line,
                self.message,
                src.as_ref()
            )
        } else {
            write!(f, "{}:{} {}", self.file, self.line, self.message)
        }
    }
}

impl Error for XErr {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        if let Some(src) = &self.source {
            return Some(src.as_ref());
        }
        None
    }
}

macro_rules! wrap {
    // Base case:
    ($err:expr) => (Err($crate::error::XErr {
        message: "an error occurred".to_string(),
        file: file!().to_string(),
        line: line!() as u64,
        source: Some($err.into()),
    }));
    ($err:expr, $msg:expr) => (Err($crate::error::XErr {
        message: $msg.to_string(),
        file: file!().to_string(),
        line: line!() as u64,
        source: Some($err.into()),
    }));
    ($err:expr, $fmt:expr, $($arg:expr),+) => (Err($crate::error::XErr {
        message: format!($fmt, $($arg),+),
        file: file!().to_string(),
        line: line!() as u64,
        source: Some($err.into()),
    }));
}

macro_rules! better_wrap {
    ($result:expr) => {
        match $result {
            Ok(value) => Ok(value),
            Err(e) => wrap!(e),
        }
    };
}

// a convenience macro for creating a Result::Err
macro_rules! raise {
    // Base case:
    ($msg:expr) => (Err($crate::error::XErr {
        message: $msg.to_string(),
        file: file!().to_string(),
        line: line!() as u64,
        source: None,
    }));
    ($fmt:expr, $($arg:expr),+) => ($Err($crate::error::XErr {
        message: format!($fmt, $($arg),+),
        file: file!().to_string(),
        line: line!() as u64,
        source: None,
    }));
}