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
//! Extensions to Rust's error system to automatically include backtraces
//! to the exact location an error originates.
//!
//! Consider this a more lightweight and less macro-based alternative to `error_chain` and similar crates. This crate
//! does not take care of actually defining the errors and their varieties, but only focuses on a thin container
//! for holding the errors and a backtrace to their origin.
//!
//! `Trace` and `TraceResult` should usually be used in place of `Result` using the macros
//! `throw!`, `try_throw!`, and `try_rethrow!`
//!
//! Although the `?` syntax was just introduced, `trace-error` is not yet compatible with it until the `Carrier` trait is stabilized. As a result,
//! all instances of `try!` and `?` should be replaced with `try_throw!` if you intend to use this crate to its fullest.
//!
//! Example:
//!
//! ```should_panic
//! #[macro_use]
//! extern crate trace_error;
//!
//! use std::error::Error;
//! use std::fmt::{Display, Formatter, Result as FmtResult};
//! use std::io;
//! use std::fs::File;
//!
//! use trace_error::*;
//!
//! pub type MyResultType<T> = TraceResult<T, MyErrorType>;
//!
//! #[derive(Debug)]
//! pub enum MyErrorType {
//!     Io(io::Error),
//!     ErrorOne,
//!     ErrorTwo,
//!     //etc
//! }
//!
//! impl Display for MyErrorType {
//!     fn fmt(&self, f: &mut Formatter) -> FmtResult {
//!         write!(f, "{}", self.description())
//!     }
//! }
//!
//! impl Error for MyErrorType {
//!     fn description(&self) -> &str {
//!         match *self {
//!             MyErrorType::Io(ref err) => err.description(),
//!             MyErrorType::ErrorOne => "Error One",
//!             MyErrorType::ErrorTwo => "Error Two",
//!         }
//!     }
//! }
//!
//! impl From<io::Error> for MyErrorType {
//!     fn from(err: io::Error) -> MyErrorType {
//!         MyErrorType::Io(err)
//!     }
//! }
//!
//! fn basic() -> MyResultType<i32> {
//!     //Something may throw
//!     throw!(MyErrorType::ErrorOne);
//!
//!     // Or return an Ok value
//!     Ok(42)
//! }
//!
//! fn example() -> MyResultType<()> {
//!     // Note the use of try_rethrow! for TraceResult results
//!     let meaning = try_rethrow!(basic());
//!
//!     // Prints 42 if `basic` succeeds
//!     println!("{}", meaning);
//!
//!     // Note the use of try_throw! for non-TraceResult results
//!     let some_file = try_throw!(File::open("Cargo.toml"));
//!
//!     Ok(())
//! }
//!
//! fn main() {
//!     match example() {
//!         Ok(_) => println!("Success!"),
//!         // Here, err is the Trace<E>, which can be printed normally,
//!         // showing both the error and the backtrace.
//!         Err(err) => panic!("Error: {}", err)
//!     }
//! }
//! ```
#![allow(unknown_lints, inline_always)]
#![deny(missing_docs)]

extern crate backtrace as bt;

pub mod backtrace;

use std::error::Error;
use std::ops::Deref;
use std::fmt::{Display, Formatter, Result as FmtResult};

use backtrace::{BacktraceFmt, DefaultBacktraceFmt, SourceBacktrace};

/// Alias to aid in usage with `Result`
pub type TraceResult<T, E> = Result<T, Trace<E>>;

/// Trace error that encapsulates a backtrace alongside an error value.
///
/// Trace itself does not implement `Error`, so they cannot be nested.
#[derive(Debug)]
pub struct Trace<E: Error> {
    error: E,
    backtrace: Box<SourceBacktrace>,
}

impl<E: Error> Trace<E> {
    /// Creates a new `Trace` from the given error and backtrace
    #[inline]
    pub fn new(error: E, backtrace: Box<SourceBacktrace>) -> Trace<E> {
        Trace { error: error, backtrace: backtrace }
    }

    /// Consume self and return the inner error value
    #[inline]
    pub fn into_error(self) -> E {
        self.error
    }

    /// Get a reference to the inner backtrace
    #[inline]
    pub fn backtrace(&self) -> &SourceBacktrace {
        &*self.backtrace
    }

    /// Format the error and backtrace
    pub fn format<Fmt: BacktraceFmt>(&self, header: bool, reverse: bool) -> String {
        format!("{}\n{}", self.error, self.backtrace.format::<Fmt>(header, reverse))
    }

    /// Convert the inner error of type `E` into type `O`
    #[inline]
    pub fn convert<O: Error>(self) -> Trace<O> where O: From<E> {
        Trace {
            error: From::from(self.error),
            backtrace: self.backtrace
        }
    }
}

unsafe impl<E: Error> Send for Trace<E> where E: Send {}

impl<E: Error> Deref for Trace<E> {
    type Target = E;

    #[inline]
    fn deref(&self) -> &E {
        &self.error
    }
}

impl<E: Error> Display for Trace<E> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "{}", self.format::<DefaultBacktraceFmt>(true, false))
    }
}

/// Creates a new `Result::Err(Trace<E>)` and immediately returns it
#[macro_export]
macro_rules! throw {
    ($err:expr) => {
        return ::std::result::Result::Err($crate::Trace::new(
            ::std::convert::From::from($err),
            ::std::boxed::Box::new($crate::backtrace::SourceBacktrace::new(line!(), file!()))
        ))
    }
}

/// Like `try!`, but invokes `throw!` on the error value if it exists, converting it to `Result::Err(Trace<E>)`
///
/// Note that the backtrace will only go as far as the location this macro was invoked
///
/// This macro will try to call `From::from` on the error to convert it if necessary, just like `try!`
#[macro_export]
macro_rules! try_throw {
    ($res:expr) => (match $res {
        ::std::result::Result::Ok(val) => val,
        ::std::result::Result::Err(err) => { throw!(err) }
    })
}

#[doc(hidden)]
#[inline(always)]
pub fn _assert_trace_result<T, E: Error>(res: TraceResult<T, E>) -> TraceResult<T, E> {
    res
}

/// Like `try_throw!`, but designed for `TraceResult`s, as it keeps the previous trace.
///
/// This macro will try to call `Trace::convert` on the trace to convert the inner error if necessary,
/// similarly to `try!`
#[macro_export]
macro_rules! try_rethrow {
    ($res:expr) => (match $crate::_assert_trace_result($res) {
        ::std::result::Result::Ok(val) => val,
        ::std::result::Result::Err(err) => {
            return ::std::result::Result::Err(err.convert())
        }
    })
}