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
#![cfg_attr(feature = "nightly", feature(try_trait_v2))]
#[cfg(feature = "nightly")]
pub mod nightly;

use std::{
    backtrace::{Backtrace, BacktraceStatus},
    cell::RefCell,
    error::Error,
};

thread_local! {
    static BACKTRACE: RefCell<Option<Backtrace>> = const { RefCell::new(None) };
}

fn print_backtrace(backtrace: &Backtrace) {
    let backtrace_string = backtrace.to_string();

    let mut backtrace_lines = backtrace_string.lines();
    backtrace_lines.next();
    backtrace_lines.next();
    let backtrace_string: String = backtrace_lines.map(|x| x.to_owned() + "\n").collect();

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

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!(),
        }

        BACKTRACE.set(Some(backtrace));

        self
    }

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

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

        let backtrace = BACKTRACE.take();
        if let Some(backtrace) = backtrace {
            print_backtrace(&backtrace);
        }

        self
    }

    fn handle_error(self) -> Self
    where
        Self: Sized,
    {
        BACKTRACE.take();

        self
    }

    fn is_error(&self) -> bool;
}

impl<T, E> ErrorBacktrace for core::result::Result<T, E> {
    fn is_error(&self) -> bool {
        self.is_err()
    }
}

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

impl ErrorBacktrace for dyn Error {
    fn is_error(&self) -> bool {
        true
    }
}