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

mod backtrace;
mod context;

mod wrapper;
pub use wrapper::OpaqueError;

/// Extends the `Result` and `Option` types with methods for adding context to errors.
///
/// See the [module level documentation](crate::error) for more information.
///
/// # Examples
///
/// ```
/// use rama_error::ErrorContext;
///
/// let result = "hello".parse::<i32>().context("parse integer");
/// assert_eq!("parse integer\r\n ↪ invalid digit found in string", result.unwrap_err().to_string());
/// ```
pub trait ErrorContext: private::SealedErrorContext {
    /// The resulting contexct type after adding context to the contained error.
    type Context;

    /// Add a static context to the contained error.
    fn context<M>(self, context: M) -> Self::Context
    where
        M: Display + Send + Sync + 'static;

    /// Lazily add a context to the contained error, if it exists.
    fn with_context<C, F>(self, context: F) -> Self::Context
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C;
}

impl<T, E> ErrorContext for Result<T, E>
where
    E: std::error::Error + Send + Sync + 'static,
{
    type Context = Result<T, OpaqueError>;

    fn context<M>(self, context: M) -> Self::Context
    where
        M: Display + Send + Sync + 'static,
    {
        self.map_err(|error| error.context(context))
    }

    fn with_context<C, F>(self, context: F) -> Self::Context
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C,
    {
        self.map_err(|error| error.context(context()))
    }
}

impl<T> ErrorContext for Option<T> {
    type Context = Result<T, OpaqueError>;

    fn context<M>(self, context: M) -> Self::Context
    where
        M: Display + Send + Sync + 'static,
    {
        match self {
            Some(value) => Ok(value),
            None => Err(wrapper::MessageError("Option is None").context(context)),
        }
    }

    fn with_context<C, F>(self, context: F) -> Self::Context
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C,
    {
        match self {
            Some(value) => Ok(value),
            None => Err(wrapper::MessageError("Option is None").with_context(context)),
        }
    }
}

/// Extends the `Error` type with methods for working with errorss.
///
/// See the [module level documentation](crate::error) for more information.
///
/// # Examples
///
/// ```
/// use rama_error::{BoxError, ErrorExt, ErrorContext};
///
/// #[derive(Debug)]
/// struct CustomError;
///
/// impl std::fmt::Display for CustomError {
///  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
///    write!(f, "Custom error")
///  }
/// }
///
/// impl std::error::Error for CustomError {}
///
/// let error = CustomError.context("whoops");
/// assert_eq!(error.to_string(), "whoops\r\n ↪ Custom error");
/// ```
pub trait ErrorExt: private::SealedErrorExt {
    /// Wrap the error in a context.
    ///
    /// # Examples
    ///
    /// ```
    /// use rama_error::ErrorExt;
    ///
    /// let error = std::io::Error::new(std::io::ErrorKind::Other, "oh no!").context("do I/O");
    /// assert_eq!(error.to_string(), "do I/O\r\n ↪ oh no!");
    /// ```
    fn context<M>(self, context: M) -> OpaqueError
    where
        M: Display + Send + Sync + 'static;

    /// Lazily wrap the error with a context.
    ///
    /// # Examples
    ///
    /// ```
    /// use rama_error::ErrorExt;
    ///
    /// let error = std::io::Error::new(std::io::ErrorKind::Other, "oh no!").with_context(|| format!(
    ///    "do I/O ({})", 42,
    /// ));
    /// assert_eq!(error.to_string(), "do I/O (42)\r\n ↪ oh no!");
    /// ```
    fn with_context<C, F>(self, context: F) -> OpaqueError
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C;

    /// Add a [`Backtrace`][std::backtrace::Backtrace] to the error.
    ///
    /// # Examples
    ///
    /// ```
    /// use rama_error::ErrorExt;
    ///
    /// let error = std::io::Error::new(std::io::ErrorKind::Other, "oh no!").backtrace();
    /// println!("{}", error);
    /// ```
    fn backtrace(self) -> OpaqueError;

    /// Convert the error into an [`OpaqueError`].
    ///
    /// # Examples
    ///
    /// ```
    /// use rama_error::ErrorExt;
    ///
    /// let error = std::io::Error::new(std::io::ErrorKind::Other, "oh no!").into_opaque();
    /// assert_eq!(error.to_string(), "oh no!");
    /// ```
    fn into_opaque(self) -> OpaqueError;
}

impl<Error: std::error::Error + Send + Sync + 'static> ErrorExt for Error {
    fn context<M>(self, context: M) -> OpaqueError
    where
        M: Display + Send + Sync + 'static,
    {
        OpaqueError::from_std(context::ContextError {
            context,
            error: self,
        })
    }

    fn with_context<C, F>(self, context: F) -> OpaqueError
    where
        C: Display + Send + Sync + 'static,
        F: FnOnce() -> C,
    {
        OpaqueError::from_std(context::ContextError {
            context: context(),
            error: self,
        })
    }

    fn backtrace(self) -> OpaqueError {
        OpaqueError::from_std(backtrace::BacktraceError::new(self))
    }

    fn into_opaque(self) -> OpaqueError {
        OpaqueError::from_std(self)
    }
}

mod private {
    pub trait SealedErrorContext {}

    impl<T, E> SealedErrorContext for Result<T, E> where E: std::error::Error + Send + Sync + 'static {}
    impl<T> SealedErrorContext for Option<T> {}

    pub trait SealedErrorExt {}

    impl<Error: std::error::Error + Send + Sync + 'static> SealedErrorExt for Error {}
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::BoxError;

    #[test]
    fn message_error_context() {
        let error = wrapper::MessageError("foo").context("context");
        assert_eq!(error.to_string(), "context\r\n ↪ foo");
    }

    #[test]
    fn box_error_context() {
        let error = Box::new(wrapper::MessageError("foo"));
        let error = error.context("context");
        assert_eq!(error.to_string(), "context\r\n ↪ foo");
    }

    #[derive(Debug)]
    struct CustomError;

    impl std::fmt::Display for CustomError {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "Custom error")
        }
    }

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

    #[derive(Debug)]
    struct WrapperError(BoxError);

    impl std::fmt::Display for WrapperError {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "Wrapper error")
        }
    }

    impl std::error::Error for WrapperError {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(self.0.as_ref())
        }
    }

    #[test]
    fn test_wrapper_error_source() {
        let error = WrapperError(Box::new(CustomError))
            .context("foo")
            .backtrace();
        let source = std::error::Error::source(&error).unwrap();
        assert!(source.downcast_ref::<CustomError>().is_some());
    }

    #[test]
    fn custom_error_backtrace() {
        let error = CustomError;
        let error = error.backtrace();

        assert!(error.to_string().starts_with("Initial error\r\n ↪"));
    }
}