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
//! An experimental new error-handling library.
//!
//! The primary items exported by this library are:
//!
//! - `Fail`: a new trait for custom error types in Rust.
//! - `Error`: a wrapper around `Fail` types to make it easy to coalesce them
//!   at higher levels.
//!
//! As a general rule, library authors should create their own error types and
//! implement `Fail` for them, whereas application authors should primarily
//! deal with the `Error` type. There are exceptions to this rule, though, in
//! both directions, and users should do whatever seems most appropriate to
//! their situation.
#![cfg_attr(not(feature = "std"), no_std)]
#![deny(missing_docs)]

macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
macro_rules! without_std { ($($i:item)*) => ($(#[cfg(not(feature = "std"))]$i)*) }

mod backtrace;
mod compat;
mod context;
mod result_ext;

use core::any::TypeId;
use core::fmt::{Display, Debug};

pub use backtrace::Backtrace;
pub use compat::Compat;
pub use context::Context;
pub use result_ext::ResultExt;

with_std! {
    extern crate core;

    mod sync_failure;
    pub use sync_failure::SyncFailure;

    mod error;

    use std::error::Error as StdError;

    pub use error::Error;

    mod error_message;
    pub use error_message::err_msg;
}


/// The `Fail` trait.
///
/// Implementors of this trait are called 'failures'.
///
/// All error types should implement `Fail`, which provides a baseline of
/// functionality that they all share.
///
/// `Fail` has no required methods, but it does require that your type
/// implement several other traits:
///
/// - `Display`: to print a user-friendly representation of the error.
/// - `Debug`: to print a verbose, developer-focused representation of the
///   error.
/// - `Send + Sync`: Your error type is required to be safe to transfer to and
///   reference from another thread
///
/// Additionally, all failures must be `'static`. This enables downcasting.
///
/// `Fail` provides several methods with default implementations. Two of these
/// may be appropriate to override depending on the definition of your
/// particular failure: the `cause` and `backtrace` methods.
///
/// The `failure_derive` crate provides a way to derive the `Fail` trait for
/// your type. Additionally, all types that already implement
/// `std::error::Error`, and are also `Send`, `Sync`, and `'static`, implement
/// `Fail` by a blanket impl.
pub trait Fail: Display + Debug + Send + Sync + 'static {
    /// Returns a reference to the underlying cause of this failure, if it
    /// is an error that wraps other errors.
    ///
    /// Returns `None` if this failure does not have another error as its
    /// underlying cause. By default, this returns `None`.
    ///
    /// This should **never** return a reference to `self`, but only return
    /// `Some` when it can return a **different** failure. Users may loop
    /// over the cause chain, and returning `self` would result in an infinite
    /// loop.
    fn cause(&self) -> Option<&Fail> {
        None
    }

    /// Returns a reference to the `Backtrace` carried by this failure, if it
    /// carries one.
    ///
    /// Returns `None` if this failure does not carry a backtrace. By
    /// default, this returns `None`.
    fn backtrace(&self) -> Option<&Backtrace> {
        None
    }

    /// Provides context for this failure.
    ///
    /// This can provide additional information about this error, appropriate
    /// to the semantics of the current layer. That is, if you have a
    /// lower-level error, such as an IO error, you can provide additional context
    /// about what that error means in the context of your function. This
    /// gives users of this function more information about what has gone
    /// wrong.
    ///
    /// This takes any type that implements `Display`, as well as
    /// `Send`/`Sync`/`'static`. In practice, this means it can take a `String`
    /// or a string literal, or another failure, or some other custom context-carrying
    /// type.
    fn context<D>(self, context: D) -> Context<D> where
        D: Display + Send + Sync + 'static,
        Self: Sized,
    {
        Context::with_err(context, self)
    }

    /// Wraps this failure in a compatibility wrapper that implements
    /// `std::error::Error`.
    ///
    /// This allows failures  to be compatible with older crates that
    /// expect types that implement the `Error` trait from `std::error`.
    fn compat(self) -> Compat<Self> where Self: Sized {
        Compat { error: self }
    }

    /// Returns the "root cause" of this `Fail` - the last value in the
    /// cause chain which does not return an underlying `cause`.
    ///
    /// If this type does not have a cause, `self` is returned, because
    /// it is its own root cause.
    fn root_cause(&self) -> &Fail where Self: Sized {
        find_root_cause(self)
    }

    #[doc(hidden)]
    fn __private_get_type_id__(&self) -> TypeId {
        TypeId::of::<Self>()
    }
}

impl Fail {
    /// Attempts to downcast this failure to a concrete type by reference.
    ///
    /// If the underlying error is not of type `T`, this will return `None`.
    pub fn downcast_ref<T: Fail>(&self) -> Option<&T> {
        if self.__private_get_type_id__() == TypeId::of::<T>() {
            unsafe { Some(&*(self as *const Fail as *const T)) }
        } else {
            None
        }
    }

    /// Attempts to downcast this failure to a concrete type by mutable
    /// reference.
    ///
    /// If the underlying error is not of type `T`, this will return `None`.
    pub fn downcast_mut<T: Fail>(&mut self) -> Option<&mut T> {
        if self.__private_get_type_id__() == TypeId::of::<T>() {
            unsafe { Some(&mut *(self as *mut Fail as *mut T)) }
        } else {
            None
        }
    }


    /// Returns the "root cause" of this `Fail` - the last value in the
    /// cause chain which does not return an underlying `cause`.
    ///
    /// If this type does not have a cause, `self` is returned, because
    /// it is its own root cause.
    pub fn root_cause(&self) -> &Fail {
        find_root_cause(self)
    }

    /// Returns a iterator over the causes of this `Fail` with it self
    /// as the first item
    pub fn causes(&self) -> Causes {
        Causes { fail: Some(self) }
    }
}

#[cfg(feature = "std")]
impl<E: StdError + Send + Sync + 'static> Fail for E { }

/// A iterator over the causes of a `Fail`
pub struct Causes<'f> {
    fail: Option<&'f Fail>,
}

impl<'f> Iterator for Causes<'f> {
    type Item = &'f Fail;
    fn next(&mut self) -> Option<&'f Fail> {
        self.fail.map(|fail| {
            self.fail = fail.cause();
            fail
        })
    }
}

fn find_root_cause(mut fail: &Fail) -> &Fail {
    while let Some(cause) = fail.cause() {
        fail = cause;
    }

    fail
}