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
use self::Kind::*;

use http::status::StatusCode;

/// Errors that can happen while extracting data from an HTTP request.
#[derive(Debug)]
pub struct Error {
    kind: Kind,
}

#[derive(Debug)]
enum Kind {
    Missing,
    Invalid(String),
    Web(::Error),
}

impl Error {
    /// The data is missing from the HTTP request.
    pub fn missing_argument() -> Error {
        Error { kind: Missing }
    }

    /// Returns `true` when the error represents missing data from the HTTP
    /// request.
    pub fn is_missing_argument(&self) -> bool {
        match self.kind {
            Missing => true,
            _ => false,
        }
    }

    /// The data is in an invalid format and cannot be extracted.
    pub fn invalid_argument<T: ToString>(reason: &T) -> Error {
        Error { kind: Invalid(reason.to_string()) }
    }

    /// Returns `true` when the data is in an invalid format and cannot be
    /// extracted.
    pub fn is_invalid_argument(&self) -> bool {
        match self.kind {
            Invalid(_) => true,
            _ => false,
        }
    }

    pub(crate) fn internal_error() -> Error {
        ::Error::from(StatusCode::BAD_REQUEST).into()
    }
}

impl From<Error> for ::Error {
    fn from(err: Error) -> Self {
        match err.kind {
            Missing | Invalid(_) => ::Error::from(StatusCode::BAD_REQUEST),
            Web(err) => err,
        }
    }
}

impl From<::Error> for Error {
    fn from(err: ::Error) -> Self {
        Error { kind: Web(err) }
    }
}