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
use data_encoding;
use std::{error, fmt, io, result, sync};

use bson;
use object_id;
use collection::error::{WriteException, BulkWriteException};
use util::textnonce;

/// A type for results generated by MongoDB related functions, where the Err type is
/// `mongodb::Error`.
pub type Result<T> = result::Result<T, Error>;

#[derive(Debug)]
pub enum MaliciousServerErrorType {
    InvalidRnonce,
    InvalidServerSignature,
    NoServerSignature,
}

impl fmt::Display for MaliciousServerErrorType {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MaliciousServerErrorType::InvalidRnonce => {
                fmt.write_str("The server returned an invalid rnonce during authentication")
            }
            MaliciousServerErrorType::InvalidServerSignature => {
                fmt.write_str("The server returned an invalid signature during authentication")
            }
            MaliciousServerErrorType::NoServerSignature => {
                fmt.write_str("The server did not sign its reponse during authentication")
            }
        }
    }
}

/// The error type for MongoDB operations.
#[derive(Debug)]
pub enum Error {
    /// I/O operation errors of `Read`, `Write`, `Seek`, and associated traits.
    IoError(io::Error),
    /// A BSON struct could not be encoded.
    EncoderError(bson::encode::EncodeError),
    /// A BSON struct could not be decoded.
    DecoderError(bson::decode::DecodeError),
    /// An ObjectId could not be generated.
    OIDError(object_id::Error),
    /// A hexadecimal string could not be converted to bytes.
    FromHexError(data_encoding::DecodeError),
    /// A single-write operation failed.
    WriteError(WriteException),
    /// A bulk-write operation failed due to one or more lower-level write-related errors.
    BulkWriteError(BulkWriteException),
    /// An invalid function or operational argument was provided.
    ArgumentError(String),
    /// A database operation failed to send or receive a reply.
    OperationError(String),
    /// A database operation returned an invalid reply.
    ResponseError(String),
    /// A cursor operation failed to return a cursor.
    CursorNotFoundError,
    /// The application failed to secure a mutex due to a poisoned lock.
    PoisonLockError,
    /// A server error with a given code.
    CodedError(CodedError),
    /// The client was unable to emit the events to the listeners due to a poisoned lock;
    /// all event listeners were dropped, so they will have to be registered again. If the
    /// client is unable to emit a failure result, the error it failed to report is bundled
    /// into the `EventListenerError`.
    EventListenerError(Option<Box<Error>>),
    /// The server that the client is attempting to authenticate to does not actually have
    /// the user's authentication information stored.
    MaliciousServerError(MaliciousServerErrorType),
    /// A standard error with a string description;
    /// a more specific error should generally be used.
    DefaultError(String),
    /// TextNonce error
    TextNonceError(textnonce::Error),
}

impl<'a> From<Error> for io::Error {
    fn from(err: Error) -> io::Error {
        io::Error::new(io::ErrorKind::Other, err)
    }
}

impl<'a> From<&'a str> for Error {
    fn from(s: &str) -> Error {
        Error::DefaultError(s.to_string())
    }
}

impl From<String> for Error {
    fn from(s: String) -> Error {
        Error::DefaultError(s.to_string())
    }
}

impl From<WriteException> for Error {
    fn from(err: WriteException) -> Error {
        Error::WriteError(err)
    }
}

impl From<BulkWriteException> for Error {
    fn from(err: BulkWriteException) -> Error {
        Error::BulkWriteError(err)
    }
}

impl From<bson::encode::EncodeError> for Error {
    fn from(err: bson::encode::EncodeError) -> Error {
        Error::EncoderError(err)
    }
}

impl From<bson::decode::DecodeError> for Error {
    fn from(err: bson::decode::DecodeError) -> Error {
        Error::DecoderError(err)
    }
}

impl From<object_id::Error> for Error {
    fn from(err: object_id::Error) -> Error {
        Error::OIDError(err)
    }
}

impl From<data_encoding::DecodeError> for Error {
    fn from(err: data_encoding::DecodeError) -> Error {
        Error::FromHexError(err)
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        Error::IoError(err)
    }
}

impl<T> From<sync::PoisonError<T>> for Error {
    fn from(_: sync::PoisonError<T>) -> Error {
        Error::PoisonLockError
    }
}

impl From<textnonce::Error> for Error {
    fn from(err : textnonce::Error) -> Error {
        Error::TextNonceError(err)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::WriteError(ref inner) => inner.fmt(fmt),
            Error::BulkWriteError(ref inner) => inner.fmt(fmt),
            Error::EncoderError(ref inner) => inner.fmt(fmt),
            Error::DecoderError(ref inner) => inner.fmt(fmt),
            Error::OIDError(ref inner) => inner.fmt(fmt),
            Error::FromHexError(ref inner) => inner.fmt(fmt),
            Error::IoError(ref inner) => inner.fmt(fmt),
            Error::ArgumentError(ref inner) => inner.fmt(fmt),
            Error::OperationError(ref inner) => inner.fmt(fmt),
            Error::ResponseError(ref inner) => inner.fmt(fmt),
            Error::CursorNotFoundError => write!(fmt, "No cursor found for cursor operation."),
            Error::PoisonLockError => {
                write!(fmt, "Socket lock poisoned while attempting to access.")
            }
            Error::CodedError(ref err) => write!(fmt, "{}", err),
            Error::EventListenerError(ref err) => {
                match *err {
                    Some(ref e) => {
                        write!(fmt,
                               "Unable to emit failure due to poisoned lock; failure: {}",
                               e)
                    }
                    None => write!(fmt, "Unable to emit failure due to poisoned lock"),
                }
            }
            Error::MaliciousServerError(ref err) => write!(fmt, "{}", err),
            Error::DefaultError(ref inner) => inner.fmt(fmt),
            Error::TextNonceError(ref inner) => inner.fmt(fmt),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::WriteError(ref inner) => inner.description(),
            Error::BulkWriteError(ref inner) => inner.description(),
            Error::EncoderError(ref inner) => inner.description(),
            Error::DecoderError(ref inner) => inner.description(),
            Error::OIDError(ref inner) => inner.description(),
            Error::FromHexError(ref inner) => inner.description(),
            Error::IoError(ref inner) => inner.description(),
            Error::CursorNotFoundError => "No cursor found for cursor operation.",
            Error::PoisonLockError => "Socket lock poisoned while attempting to access.",
            Error::CodedError(ref err) => err.to_str(),
            Error::EventListenerError(ref err) => {
                match *err {
                    Some(_) => "Due to a poisoned lock on the listeners, unable to emit failure",
                    None => "Due to a poisoned lock on the listeners, unable to emit event",
                }
            }
            Error::MaliciousServerError(ref err) => {
                match *err {
                    MaliciousServerErrorType::InvalidRnonce => {
                        "The server returned an invalid rnonce during authentication"
                    }
                    MaliciousServerErrorType::InvalidServerSignature => {
                        "The server returned an invalid signature during authentication"
                    }
                    MaliciousServerErrorType::NoServerSignature => {
                        "The server did not sign its reponse during authentication"
                    }
                }
            }
            Error::ArgumentError(ref inner) |
            Error::OperationError(ref inner) |
            Error::ResponseError(ref inner) |
            Error::DefaultError(ref inner) => inner,
            Error::TextNonceError(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::WriteError(ref inner) => Some(inner),
            Error::BulkWriteError(ref inner) => Some(inner),
            Error::EncoderError(ref inner) => Some(inner),
            Error::DecoderError(ref inner) => Some(inner),
            Error::OIDError(ref inner) => Some(inner),
            Error::FromHexError(ref inner) => Some(inner),
            Error::IoError(ref inner) => Some(inner),
            Error::ArgumentError(_) |
            Error::OperationError(_) |
            Error::ResponseError(_) |
            Error::CursorNotFoundError |
            Error::PoisonLockError |
            Error::CodedError(_) |
            Error::EventListenerError(_) |
            Error::MaliciousServerError(_) |
            Error::DefaultError(_) => None,
            Error::TextNonceError(ref inner) => Some(inner),
        }
    }
}

#[derive(Debug)]
pub struct CodedError {
    pub code: i32,
    pub errmsg: String
}

impl CodedError {
    fn to_str(&self) -> &str {
        &self.errmsg
    }
}

impl fmt::Display for CodedError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_fmt(format_args!("{{code: {}, errmsg: {}}}", self.code, self.errmsg))
    }
}