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
use std::backtrace::{Backtrace, BacktraceStatus};

pub trait ErrorBacktrace {
    fn trace(self) -> Self
    where
        Self: Sized,
    {
        #[cfg(all(feature = "debug-only", not(debug_assertions)))]
        return self;

        if !self.is_error() {
            return self;
        }

        let backtrace = Backtrace::capture();
        match backtrace.status() {
            BacktraceStatus::Unsupported => {
                println!("Backtrace is not supported on this platform");
            }
            BacktraceStatus::Disabled => {
                return self;
            }
            BacktraceStatus::Captured => {}
            _ => unreachable!(),
        }

        println!("Error Backtrace:\n{}\n", backtrace);

        self
    }

    fn is_error(&self) -> bool;
}

impl<T1, T2> ErrorBacktrace for Result<T1, T2> {
    fn is_error(&self) -> bool {
        self.is_err()
    }
}

impl<T1> ErrorBacktrace for Option<T1> {
    fn is_error(&self) -> bool {
        self.is_none()
    }
}