error_backtrace/
lib.rs

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
/*! Attaches backtraces to errrors.
 * 
 * Typical usage is automatic via `?`:
 ```
struct Error;
 
fn maybe_error() -> Result<(), Error> {
    error_source()?;
    Ok(())
}

fn error_source() -> Result<(), Error> {
    Err(Error {}.into())
}
```

If you need to convert the error first, check out the `IntoTraced` trait.
 */
use std::{
    error::Error,
    fmt::Debug,
    ops::{Deref, DerefMut},
};

#[cfg(feature = "clean-backtrace")]
use backtrace::Backtrace;
#[cfg(not(feature = "clean-backtrace"))]
use std::backtrace::Backtrace;

pub type Result<T, E> = std::result::Result<T, Backtraced<E>>;

/** Allows converting a `Result` into a `error_backtrace::Result` explicitly.

Use it when you can't just use `?`, like when you need to convert into a different type of error first.

```
use error_backtrace::IntoTraced;
fn out() -> error_backtrace::Result<(), ()> {
    let fail: Result<(), ()> = Err(());
    fail.with_trace()
}
```
*/
pub trait IntoTraced {
    type Value;
    type Error;
    fn with_trace(self) -> Result<Self::Value, Self::Error>;
}

impl<T, E> IntoTraced for std::result::Result<T, E> {
    type Value = T;
    type Error = E;
    fn with_trace(self) -> Result<Self::Value, Self::Error> {
        self.map_err(|e| e.into())
    }
}

pub struct Backtraced<E> {
    pub inner: E,
    backtrace: Backtrace,
}

impl<E> Debug for Backtraced<E>
where
    E: Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // .unwrap() doesn't use alternate.
        // .unwrap() is the most relevant use of this type, so make sure the backtrace is present then
        if !f.alternate() {
            writeln!(
                f,
                "{:?}\n\nBacktrace:\n{}",
                &self.inner,
                format_backtrace(&self.backtrace)
            )
        } else {
            writeln!(f, "{:?}", &self.inner)
        }
    }
}

impl<E> From<E> for Backtraced<E> {
    fn from(value: E) -> Self {
        Backtraced {
            inner: value,
            #[cfg(feature = "clean-backtrace")]
            backtrace: Backtrace::new(),
            #[cfg(not(feature = "clean-backtrace"))]
            backtrace: Backtrace::capture(),
        }
    }
}

impl<T> Backtraced<T> {
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Backtraced<U> {
        Backtraced {
            inner: f(self.inner),
            backtrace: self.backtrace,
        }
    }

    pub fn map_into<U: From<T>>(self) -> Backtraced<U> {
        Backtraced {
            inner: self.inner.into(),
            backtrace: self.backtrace,
        }
    }
}

pub trait ResultBacktrace {
    type Value;
    type Error;
    
    /// Maps the traced error. Use this instead of map_err.
    fn map_trace<E>(
        self,
        f: impl FnOnce(Self::Error) -> E,
    ) -> std::result::Result<Self::Value, Backtraced<E>>;
    
    /** Convert the error type using into().
     
    ```
    use std::io;
    use error_backtrace::{Result, ResultBacktrace};

    struct MyError(io::Error);
    
    impl From<io::Error> for MyError {
        fn from(value: io::Error) -> Self {
            Self(value)
        }
    }
    
    fn convert(res: Result<(), io::Error>) -> Result<(), MyError> {
        res.map_trace_into()
    }
    ```
    */
    fn map_trace_into<E: From<Self::Error>>(self)
        -> std::result::Result<Self::Value, Backtraced<E>>;

    /// Print the current backtrace.
    fn backtrace(self) -> Self;
}

impl<T, E> ResultBacktrace for std::result::Result<T, Backtraced<E>> {
    type Value = T;
    type Error = E;
    fn map_trace<F>(
        self,
        f: impl FnOnce(Self::Error) -> F,
    ) -> std::result::Result<Self::Value, Backtraced<F>> {
        self.map_err(|e| Backtraced::<E>::map(e, f))
    }

    fn map_trace_into<F: From<Self::Error>>(self)
        -> std::result::Result<Self::Value, Backtraced<F>>
    {
        self.map_trace(F::from)
    }
    
    fn backtrace(self) -> Self {
        #[cfg(all(feature = "debug-only", not(debug_assertions)))]
        return self;

        let Err(ref error) = self else {
            return self;
        };

        println!("Error backtrace:\n{}", format_backtrace(&error.backtrace));

        self
    }
}

#[cfg(not(feature = "clean-backtrace"))]
fn format_backtrace(backtrace: &Backtrace) -> String {
    format!("{backtrace:?}")
}

#[cfg(feature = "clean-backtrace")]
fn clean_backtrace(backtrace: &Backtrace) -> Backtrace {
    let frames = &backtrace.frames()[1..];
    let bt = Backtrace::new();
    let current_frames: Vec<_> = bt.frames().iter().map(|f| f.ip()).collect();

    let frames: Vec<_> = frames
        .iter()
        // Skip .into()
        .filter(|f| {
            f.symbols()
                .get(0)
                .map(|symbol| {
                    symbol
                        .name()
                        .map(|name| {
                            let formated_name = format!("{:#?}", name);
                            // Not sure if this is the case for all systems
                            &formated_name != "<T as core::convert::Into<U>>::into"
                        })
                        .unwrap_or(true)
                })
                .unwrap_or(true)
        })
        // This skips everything before backtrace was called, including everything before main.
        .filter(|x| !current_frames.contains(&x.ip()))
        .cloned()
        .collect();

    frames.to_vec().into()
}


#[cfg(feature = "clean-backtrace")]
fn format_backtrace(backtrace: &Backtrace) -> String {
    let backtrace: Backtrace = clean_backtrace(backtrace);
    format!("{backtrace:?}")
}

// Extra

impl<E> Deref for Backtraced<E> {
    type Target = E;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<E> DerefMut for Backtraced<E> {
    fn deref_mut(&mut self) -> &mut E {
        &mut self.inner
    }
}

impl<E: PartialEq> PartialEq for Backtraced<E> {
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

/// A generic error, use instead of a Box<dyn Error>.
///
/// Use .into() to get the Box<dyn Error> back.
///
/// Converting an `E: Error` into `Box<dyn Error>`, requires magic
/// because `Box<dyn Error>` itself is `Error`.
/// That conflicts with builtin `impl<T> From<T> for T;`
///
/// This struct must not implement Error, so it can be created from Error.
/// As the price, it must be converted back explicitly using `.into()`.
#[derive(Debug)]
pub struct GenericError(pub Box<dyn Error>);

impl GenericError {
    pub fn from_static<T: Error + 'static>(e: T) -> Self {
        Self(Box::new(e))
    }
}

impl<E: Error + 'static> From<Backtraced<E>> for Backtraced<GenericError> {
    fn from(value: Backtraced<E>) -> Self {
        Backtraced {
            inner: GenericError(value.inner.into()),
            backtrace: value.backtrace,
        }
    }
}

impl<E: Error + 'static> From<E> for Backtraced<GenericError> {
    fn from(value: E) -> Self {
        Backtraced::<E>::from(value).into()
    }
}

impl From<GenericError> for Box<dyn Error> {
    fn from(value: GenericError) -> Self {
        value.0
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use std::io;

    fn fail_io() -> io::Result<()> {
        Err(io::Error::other("simple"))
    }

    #[test]
    #[ignore = "compilation test"]
    fn fail_backtraced() -> Result<(), io::Error> {
        Err(io::Error::other("backtraced"))?
    }
    
    #[test]
    #[ignore = "compilation test"]
    fn fail_try_backtraced() -> Result<(), io::Error> {
        fail_io()?;
        Ok(())
    }
    
    #[test]
    #[ignore = "compilation test"]
    fn fail_into_backtraced() -> Result<(), io::Error> {
        use super::IntoTraced;
        fail_io().with_trace()
    }

    #[allow(dead_code)]
    #[derive(Debug)]
    struct MyError(io::Error);

    impl From<io::Error> for MyError {
        fn from(value: io::Error) -> Self {
            MyError(value)
        }
    }
    
    #[test]
    #[ignore = "compilation test"]
    fn map_err_into() -> Result<(), MyError> {
        let e = fail_into_backtraced();
        e.map_err(Backtraced::map_into)
    }

    #[test]
    #[ignore = "compilation test"]
    fn map_trace() -> Result<(), MyError> {
        let e = fail_into_backtraced();
        e.map_trace(MyError::from)
    }

    #[test]
    #[ignore = "compilation test"]
    fn map_trace_into() -> Result<(), MyError> {
        let e = fail_into_backtraced();
        e.map_trace_into()
    }
    
    #[test]
    #[ignore = "compilation test"]
    fn test_error_generic_question() -> Result<(), GenericError> {
        let out = fail_io()?;
        Ok(out)
    }

    #[test]
    #[ignore = "compilation test"]
    fn test_backtraced_generic_question() -> Result<(), GenericError> {
        let out = fail_backtraced()?;
        Ok(out)
    }
    
    fn fail_boxed() -> std::result::Result<(), Box<dyn Error>> {
        Ok(fail_io()?)
    }

    #[test]
    #[ignore = "compilation test"]
    fn concrete_to_generic() -> std::result::Result<(), GenericError> {
        Ok(fail_io().map_err(GenericError::from_static)?)
    }
    
    #[test]
    #[ignore = "compilation test"]
    fn boxed_to_generic() -> std::result::Result<(), GenericError> {
        Ok(fail_boxed().map_err(GenericError)?)
    }

    #[test]
    #[ignore = "compilation test"]
    fn literal_to_generic() -> std::result::Result<(), GenericError> {
        let e = io::Error::other("simple");
        Err(GenericError::from_static(e))
    }
    
    #[test]
    #[ignore = "compilation test"]
    fn literal_to_generic_traced() -> Result<(), GenericError> {
        let e = io::Error::other("simple");
        Ok(Err(GenericError::from_static(e))?)
    }
    
    #[test]
    #[ignore = "compilation test"]
    fn boxed_to_generic_traced() -> Result<(), GenericError> {
        Ok(fail_boxed().map_err(GenericError)?)
    }
}