rocket_config/
error.rs

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
346
347
348
349
350
351
352
353
354
355
356
#![allow(dead_code)]
//! Type representing various errors that can occur in a Rocket application.

use std::error;
use std::fmt;

/// The error type for rocket-config operations of the associated traits.
///
/// Custom instances of `Error` can be created with crafted error messages
/// and a particular value of [`rocket-config::error::ErrorKind`].
///
/// [`rocket-config::error::ErrorKind`]: enum.ErrorKind.html
pub struct Error {
    repr: Repr
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.repr, f)
    }
}

enum Repr {
    Simple(ErrorKind),
    Custom(Box<Custom>),
}

#[derive(Debug)]
struct Custom {
    kind: ErrorKind,
    error: Box<dyn error::Error+Send+Sync>,
}

/// A list specifying general categories of rocket-config error.
///
/// This list is intended to grow over time and it is not recommended to
/// exhaustively match against it.
///
/// It is used with the [`rocket-config::error::Error`] type.
///
/// [`rocket-config::error::Error`]: struct.Error.html
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum ErrorKind {
    FormatError,
    MissingValue,
    UnimplementedFormat,
    Other,
}

impl ErrorKind {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            ErrorKind::FormatError          => "format_error",
            ErrorKind::MissingValue         => "missing_value",
            ErrorKind::UnimplementedFormat  => "unimplemented_format",
            ErrorKind::Other                => "other",
        }
    }
}

/// Intended for use for errors not exposed to the user, where allocating onto
/// the heap (for normal construction via Error::new) is too costly.
impl From<ErrorKind> for Error {
    /// Converts an [`ErrorKind`] into an [`Error`].
    ///
    /// This conversion allocates a new error with a simple representation of error kind.
    /// [`ErrorKind`]: ./enum.ErrorKind.html
    /// [`Error`]: ./struct.Error.html
    #[inline]
    fn from(kind: ErrorKind) -> Error {
        Error {
            repr: Repr::Simple(kind)
        }
    }
}

impl Error {
    /// Creates a new I/O error from a known kind of error as well as an
    /// arbitrary error payload.
    ///
    /// This function is used to generically create I/O errors which do not
    /// originate from the OS itself. The `error` argument is an arbitrary
    /// payload which will be contained in this `Error`.
    pub fn new<E>(kind: ErrorKind, error: E) -> Error
        where E: Into<Box<dyn error::Error+Send+Sync>>
    {
        Self::_new(kind, error.into())
    }

    fn _new(kind: ErrorKind, error: Box<dyn error::Error+Send+Sync>) -> Error {
        Error {
            repr: Repr::Custom(Box::new(Custom {
                kind,
                error,
            }))
        }
    }

    /// Returns a reference to the inner error wrapped by this error (if any).
    ///
    /// If this `Error` was constructed via `new` then this function will
    /// return `Some`, otherwise it will return `None`.
    pub fn get_ref(&self) -> Option<&(dyn error::Error+Send+Sync+'static)> {
        match self.repr {
            Repr::Simple(..) => None,
            Repr::Custom(ref c) => Some(&*c.error),
        }
    }

    /// Returns a mutable reference to the inner error wrapped by this error
    /// (if any).
    ///
    /// If this `Error` was constructed via `new` then this function will
    /// return `Some`, otherwise it will return `None`.
    pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error+Send+Sync+'static)> {
        match self.repr {
            Repr::Simple(..) => None,
            Repr::Custom(ref mut c) => Some(&mut *c.error),
        }
    }

    /// Consumes the `Error`, returning its inner error (if any).
    ///
    /// If this `Error` was constructed via `new` then this function will
    /// return `Some`, otherwise it will return `None`.
    pub fn into_inner(self) -> Option<Box<dyn error::Error+Send+Sync>> {
        match self.repr {
            Repr::Simple(..) => None,
            Repr::Custom(c) => Some(c.error)
        }
    }

    /// Returns the corresponding `ErrorKind` for this error.
    pub fn kind(&self) -> ErrorKind {
        match self.repr {
            Repr::Custom(ref c) => c.kind,
            Repr::Simple(kind) => kind,
        }
    }
}

impl fmt::Debug for Repr {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
            Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.repr {
            Repr::Custom(ref c) => c.error.fmt(fmt),
            Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match self.repr {
            Repr::Simple(..) => self.kind().as_str(),
            Repr::Custom(ref c) => c.error.description(),
        }
    }

    #[allow(deprecated)]
    fn cause(&self) -> Option<&dyn error::Error> {
        match self.repr {
            Repr::Simple(..) => None,
            Repr::Custom(ref c) => c.error.cause(),
        }
    }

    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self.repr {
            Repr::Simple(..) => None,
            Repr::Custom(ref c) => c.error.source(),
        }
    }
}

fn _assert_error_is_sync_send() {
    fn _is_sync_send<T: Sync+Send>() {}
    _is_sync_send::<Error>();
}

#[cfg(test)]
mod tests {
    use std::error::Error as _;
    use super::{Error, ErrorKind};

    #[test]
    fn custom() {
        let error = Error::new(
            ErrorKind::Other, "test error"
        );

        assert_eq!(error.kind(), ErrorKind::Other);
    }

    #[test]
    fn simple() {
        let error = Error::from(
            ErrorKind::Other
        );

        assert_eq!(error.kind(), ErrorKind::Other);
    }

    #[test]
    fn errorkind_as_str() {
        let error_format_error = Error::from(ErrorKind::FormatError);
        let error_missing_value = Error::from(ErrorKind::MissingValue);
        let error_other = Error::from(ErrorKind::Other);
        let error_unimplemented_format = Error::from(ErrorKind::UnimplementedFormat);

        assert_eq!(error_format_error.kind().as_str(), "format_error");
        assert_eq!(error_missing_value.kind().as_str(), "missing_value");
        assert_eq!(error_other.kind().as_str(), "other");
        assert_eq!(error_unimplemented_format.kind().as_str(), "unimplemented_format");
    }

    #[test]
    fn custom_get_ref() {
        let error = Error::new(ErrorKind::Other, "test error");
        let ref_error = error.get_ref();

        assert!(ref_error.is_some());
        assert_eq!(ref_error.unwrap().description(), "test error");
    }

    #[test]
    fn simple_get_ref() {
        let error = Error::from(ErrorKind::Other);

        assert!(error.get_ref().is_none());
    }

    #[test]
    fn custom_get_mut() {
        let mut error = Error::new(ErrorKind::Other, "test error");
        let ref_error = error.get_mut();

        assert!(ref_error.is_some());
        assert_eq!(ref_error.unwrap().description(), "test error");
    }

    #[test]
    fn simple_get_mut() {
        let mut error = Error::from(ErrorKind::Other);

        assert!(error.get_mut().is_none());
    }

    #[test]
    fn custom_into_inner() {
        let error = Error::new(ErrorKind::Other, "test error");
        let inner_error = error.into_inner();

        assert!(inner_error.is_some());
        assert_eq!(inner_error.unwrap().description(), "test error");
    }

    #[test]
    fn simple_into_inner() {
        let error = Error::from(ErrorKind::Other);

        assert!(error.into_inner().is_none());
    }

    #[test]
    fn custom_description() {
        let error = Error::new(ErrorKind::Other, "test error");

        assert_eq!(error.description(), "test error");
    }

    #[test]
    fn simple_description() {
        let error = Error::from(ErrorKind::Other);

        assert_eq!(error.description(), ErrorKind::Other.as_str());
    }

    #[test]
    #[allow(deprecated)]
    fn custom_cause() {
        let error = Error::new(ErrorKind::Other, "test error");
        let error_cause = error.cause();

        assert!(error_cause.is_none());
    }

    #[test]
    #[allow(deprecated)]
    fn simple_cause() {
        let error = Error::from(ErrorKind::Other);
        let error_cause = error.cause();

        assert!(error_cause.is_none());
    }

    #[test]
    fn custom_source() {
        let error = Error::new(ErrorKind::Other, "test error");
        let error_source = error.source();

        assert!(error_source.is_none());
    }

    #[test]
    fn simple_source() {
        let error = Error::from(ErrorKind::Other);
        let error_source = error.source();

        assert!(error_source.is_none());
    }

    #[test]
    fn custom_debug() {
        let error = Error::new(ErrorKind::Other, "test error");

        assert_eq!(
            format!("{:?}", error),
            "Custom { kind: Other, error: \"test error\" }"
        );
    }

    #[test]
    fn simple_debug() {
        let error = Error::from(ErrorKind::Other);

        assert_eq!(format!("{:?}", error), "Kind(Other)");
    }

    #[test]
    fn custom_display() {
        let error = Error::new(ErrorKind::Other, "test error");

        assert_eq!(format!("{}", error), "test error");
    }

    #[test]
    fn simple_display() {
        let error = Error::from(ErrorKind::Other);

        assert_eq!(format!("{}", error), "other");
    }

    #[test]
    fn assert_error_is_sync_send() {
        super::_assert_error_is_sync_send();
    }
}