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
//! `Error` and `Result` types arising out of MongoDB operations.

use std::fmt;
use std::error;
use std::result;
use std::ops::Deref;
use std::borrow::Cow;
use bson::ValueAccessError;
use backtrace::Backtrace;

/// Slightly augmented trait for backtrace-able errors.
#[allow(clippy::stutter)]
pub trait ErrorExt: error::Error {
    /// Similar to `std::error::Error::source()`, but with richer type info.
    fn reason(&self) -> Option<&(dyn ErrorExt + 'static)> {
        None
    }

    /// Returns the deepest possible backtrace, if any.
    fn backtrace(&self) -> Option<&Backtrace> {
        None
    }

    /// Structured error kind.
    fn kind(&self) -> ErrorKind;

    /// Until subtrait coercions are implemented, this helper method
    /// should return the receiver as an `&std::error::Error` trait object.
    fn as_std_error(&self) -> &(dyn error::Error + 'static);
}

/// A trait for conveniently propagating errors up the call stack.
pub trait ResultExt<T>: Sized {
    /// If this `Result` is an `Err`, then prepend the specified error
    /// to the front of the linked list of causes.
    /// ```
    /// # extern crate avocado;
    /// #
    /// # use std::error::Error as StdError;
    /// # use avocado::error::{ Error, ErrorKind, ErrorExt, Result, ResultExt };
    /// #
    /// # fn main() -> Result<()> {
    /// #
    /// let ok: Result<_> = Ok("success!");
    /// let ok_chained = ok.chain("dummy error message")?;
    /// assert_eq!(ok_chained, "success!");
    ///
    /// let err: Result<i32> = Err(Error::new(
    ///     ErrorKind::MongoDbError, "chained cause"
    /// ));
    /// let err_chained = err.chain("top-level message").unwrap_err();
    /// assert_eq!(err_chained.description(), "top-level message");
    /// assert_eq!(err_chained.kind(), ErrorKind::MongoDbError);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    fn chain<M: ErrMsg>(self, message: M) -> Result<T>;
}

/// Values that can act as or generate an error message.
pub trait ErrMsg: Sized {
    /// Convert the value to an error message.
    fn into_message(self) -> Cow<'static, str>;
}

/// Type alias for a `Result` containing an Avocado `Error`.
pub type Result<T> = result::Result<T, Error>;

impl<T, E> ResultExt<T> for result::Result<T, E> where E: ErrorExt + 'static {
    fn chain<M: ErrMsg>(self, message: M) -> Result<T> {
        self.map_err(|cause| Error::with_cause(message.into_message(), cause))
    }
}

/// Blanket `impl ErrMsg` for string literals.
impl ErrMsg for &'static str {
    fn into_message(self) -> Cow<'static, str> {
        Cow::Borrowed(self)
    }
}

/// Blanket `impl ErrMsg` for error message formatting functions.
impl<F> ErrMsg for F where F: FnOnce() -> String {
    fn into_message(self) -> Cow<'static, str> {
        Cow::Owned(self())
    }
}

/// A structured, "machine-readable" error kind.
#[allow(clippy::stutter)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ErrorKind {
    /// There was an error converting between JSON and a strongly-typed value.
    JsonTranscoding,
    /// There was an error converting a strongly-typed value to BSON.
    BsonEncoding,
    /// There was an error converting BSON to a strongly-typed value.
    BsonDecoding,
    /// This numerical value can't be represented in BSON (because,
    /// for example, it exceeds the range of `i64`)
    BsonNumberRepr,
    /// A field with the specified key was not found in the BSON document.
    MissingDocumentField,
    /// A field with the specified key was found in the BSON document,
    /// but it was of an unexpected type.
    IllTypedDocumentField,
    /// One or more ID fields (e.g. `_id` in an entity document or
    /// `inserted_id` in a MongoDB response) could not be found.
    MissingId,
    /// An `ObjectId` could not be generated.
    ObjectIdGeneration,
    /// An error that comes from the MongoDB driver.
    MongoDbError,
    /// An error coming from MongoDB, related to a single write operation.
    MongoDbWriteException,
    /// An error coming from MongoDB, related to a bulk write operation.
    MongoDbBulkWriteException,
    /// An attempt was made to convert a negative integer to a `usize`.
    IntConversionUnderflow,
    /// An attempt was made to convert an integer that is too big to a `usize`.
    IntConversionOverflow,
    /// There was an error in the BSON schema for a type.
    BsonSchema,
}

impl ErrorKind {
    /// Returns a human-readable error description for this kind.
    pub fn as_str(self) -> &'static str {
        use self::ErrorKind::*;

        match self {
            JsonTranscoding           => "JSON transcoding error",
            BsonEncoding              => "BSON encoding error",
            BsonDecoding              => "BSON decoding error",
            BsonNumberRepr            => "number not i64 nor f64",
            MissingDocumentField      => "document field not found",
            IllTypedDocumentField     => "document field of unexpected type",
            MissingId                 => "missing unique identifier",
            ObjectIdGeneration        => "an ObjectID could not be generated",
            MongoDbError              => "MongoDB error",
            MongoDbWriteException     => "MongoDB write exception",
            MongoDbBulkWriteException => "MongoDB bulk write exception",
            IntConversionUnderflow    => "integer conversion underflowed",
            IntConversionOverflow     => "integer conversion overflowed",
            BsonSchema                => "error in BSON schema",
        }
    }
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// The central error type for Avocado.
#[derive(Debug)]
pub struct Error {
    /// The structured, "machine-readable" kind of this error.
    kind: ErrorKind,
    /// The human-readable description.
    message: Cow<'static, str>,
    /// The underlying error, if any.
    cause: Option<Box<dyn ErrorExt>>,
    /// The backtrace, if any.
    backtrace: Option<Backtrace>,
}

impl Error {
    /// Creates an error with the specified kind, message, no cause,
    /// and a backtrace.
    /// ```
    /// # extern crate avocado;
    /// #
    /// # use std::error::Error as StdError;
    /// # use avocado::error::{ Error, ErrorKind, ErrorExt };
    /// #
    /// # fn main() {
    /// #
    /// let error = Error::new(ErrorKind::MissingId, "sample error message");
    /// assert_eq!(error.description(), "sample error message");
    /// assert_eq!(error.kind(), ErrorKind::MissingId);
    /// assert!(error.reason().is_none());
    /// assert!(error.backtrace().is_some());
    /// #
    /// # }
    /// ```
    pub fn new<S>(kind: ErrorKind, message: S) -> Self
        where S: Into<Cow<'static, str>>
    {
        Error {
            kind,
            message: message.into(),
            cause: None,
            backtrace: Some(Backtrace::new()),
        }
    }

    /// Creates an error with the specified message and cause. If the cause has
    /// no backtrace, this method will create it and add it to the new instance.
    /// ```
    /// # extern crate avocado;
    /// # extern crate bson;
    /// #
    /// # use std::error::Error as StdError;
    /// # use avocado::error::{ Error, ErrorExt };
    /// #
    /// # fn main() {
    /// #
    /// use bson::oid;
    ///
    /// let cause = oid::Error::HostnameError;
    /// assert!(cause.cause().is_none());
    /// assert!(cause.backtrace().is_none());
    ///
    /// let error = Error::with_cause("top-level message", cause);
    /// assert_eq!(error.description(), "top-level message");
    /// assert_eq!(error.cause().unwrap().description(),
    ///            "Failed to retrieve hostname for OID generation.");
    /// assert!(error.backtrace().is_some());
    /// #
    /// # }
    /// ```
    pub fn with_cause<S, E>(message: S, cause: E) -> Self
        where S: Into<Cow<'static, str>>,
              E: ErrorExt + 'static
    {
        let kind = cause.kind();
        let message = message.into();
        let backtrace = if cause.backtrace().is_none() {
            Some(Backtrace::new())
        } else {
            None
        };
        let cause: Option<Box<dyn ErrorExt>> = Some(Box::new(cause));

        Error { kind, message, cause, backtrace }
    }
}

impl ErrorExt for Error {
    fn reason(&self) -> Option<&(dyn ErrorExt + 'static)> {
        self.cause.as_ref().map(Deref::deref)
    }

    #[allow(clippy::or_fun_call)]
    fn backtrace(&self) -> Option<&Backtrace> {
        self.reason().and_then(ErrorExt::backtrace).or(self.backtrace.as_ref())
    }

    fn kind(&self) -> ErrorKind {
        self.kind
    }

    fn as_std_error(&self) -> &(dyn error::Error + 'static) {
        self
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}: {}", self.kind, self.message)?;

        if let Some(cause) = self.cause.as_ref() {
            write!(f, ", caused by: {}", cause)?
        }

        if let Some(backtrace) = self.backtrace.as_ref() {
            write!(f, "; {:#?}", backtrace)?
        }

        Ok(())
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        &self.message
    }

    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        self.reason().map(ErrorExt::as_std_error)
    }
}

impl From<ValueAccessError> for Error {
    fn from(error: ValueAccessError) -> Self {
        let message = match error {
            ValueAccessError::NotPresent => "missing value for key in Document",
            ValueAccessError::UnexpectedType => "ill-typed value for key in Document",
        };
        Self::with_cause(message, error)
    }
}

impl ErrorExt for ValueAccessError {
    fn kind(&self) -> ErrorKind {
        match *self {
            ValueAccessError::NotPresent => ErrorKind::MissingDocumentField,
            ValueAccessError::UnexpectedType => ErrorKind::IllTypedDocumentField,
        }
    }

    fn as_std_error(&self) -> &(dyn error::Error + 'static) {
        self
    }
}

/// Implementing `ErrorExt` and `From` boilerplate.
macro_rules! impl_error_type {
    ($ty:path, $kind:ident, $message:expr) => {
        impl From<$ty> for Error {
            fn from(error: $ty) -> Self {
                Self::with_cause($message, error)
            }
        }

        impl ErrorExt for $ty {
            fn kind(&self) -> ErrorKind {
                ErrorKind::$kind
            }

            fn as_std_error(&self) -> &(dyn error::Error + 'static) {
                self
            }
        }
    }
}

impl_error_type! { serde_json::Error,  JsonTranscoding,    "JSON transcoding error" }
impl_error_type! { bson::EncoderError, BsonEncoding,       "BSON encoding error" }
impl_error_type! { bson::DecoderError, BsonDecoding,       "BSON decoding error" }
impl_error_type! { bson::oid::Error,   ObjectIdGeneration, "ObjectId generation error" }
impl_error_type! { mongodb::Error,     MongoDbError,       "MongoDB error" }
impl_error_type! {
    mongodb::coll::error::WriteException,
    MongoDbWriteException,
    "MongoDB write exception"
}
impl_error_type! {
    mongodb::coll::error::BulkWriteException,
    MongoDbBulkWriteException,
    "MongoDB bulk write exception"
}