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
use crate::{BoxedError, DefaultFuture};
use futures::IntoFuture;
use http::StatusCode;
use std::{borrow::Cow, error, fmt};

/// The error type used by this library.
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    /// In case of a `WrongMethod` error, stores the allowed HTTP methods.
    allowed_methods: Cow<'static, [&'static http::Method]>,
    source: Option<BoxedError>,
}

impl Error {
    /// Creates an error that contains just the given [`ErrorKind`].
    ///
    /// [`ErrorKind`]: enum.ErrorKind.html
    pub fn from_kind(kind: ErrorKind) -> Self {
        Self {
            kind,
            allowed_methods: (&[][..]).into(),
            source: None,
        }
    }

    /// Creates an error from an [`ErrorKind`] and an underlying error that
    /// caused this one.
    ///
    /// # Parameters
    ///
    /// * **`kind`**: The [`ErrorKind`] describing the error.
    /// * **`source`**: The underlying error that caused this one. Needs to
    ///   implement `Into<BoxedError>`, so any type that implements
    ///   `std::error::Error + Send + Sync` can be passed.
    ///
    /// [`ErrorKind`]: enum.ErrorKind.html
    pub fn with_source<S>(kind: ErrorKind, source: S) -> Self
    where
        S: Into<BoxedError>,
    {
        Self {
            kind,
            allowed_methods: (&[][..]).into(),
            source: Some(source.into()),
        }
    }

    /// Creates an error with [`ErrorKind::WrongMethod`], given the allowed set
    /// of HTTP methods.
    ///
    /// [`ErrorKind::WrongMethod`]: enum.ErrorKind.html#variant.WrongMethod
    pub fn wrong_method<M>(allowed_methods: M) -> Self
    where
        M: Into<Cow<'static, [&'static http::Method]>>,
    {
        Self {
            kind: ErrorKind::WrongMethod,
            allowed_methods: allowed_methods.into(),
            source: None,
        }
    }

    /// Returns the [`ErrorKind`] that further describes this error.
    ///
    /// [`ErrorKind`]: enum.ErrorKind.html
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Returns the HTTP status code that most closely describes this error.
    pub fn http_status(&self) -> StatusCode {
        self.kind.http_status()
    }

    /// Creates an HTTP response for indicating this error to the client.
    ///
    /// No body will be provided (hence the `()` body type), but the caller can
    /// `map` the result to supply one.
    ///
    /// # Example
    ///
    /// Call `map` on the response to supply your own HTTP payload:
    ///
    /// ```
    /// use hyperdrive::{Error, ErrorKind};
    /// use hyper::Body;
    ///
    /// let error = Error::from_kind(ErrorKind::NoMatchingRoute);
    /// let response = error.response()
    ///     .map(|()| Body::from("oh no!"));
    /// ```
    pub fn response(&self) -> http::Response<()> {
        let mut builder = http::Response::builder();
        builder.status(self.http_status());

        if self.kind == ErrorKind::WrongMethod {
            // The spec mandates that "405 Method Not Allowed" always sends an
            // `Allow` header
            let allowed = self
                .allowed_methods
                .iter()
                .map(|method| method.as_str().to_uppercase())
                .collect::<Vec<_>>()
                .join(", ");
            builder.header(http::header::ALLOW, allowed);
        }

        builder
            .body(())
            .expect("could not build HTTP response for error")
    }

    /// Turns this error into a generic boxed future compatible with the output
    /// of `#[derive(FromRequest)]`.
    ///
    /// This is used by the code generated by `#[derive(FromRequest)]`.
    #[doc(hidden)] // not part of public API
    pub fn into_future<T: Send + 'static>(self) -> DefaultFuture<T, BoxedError> {
        Box::new(Err(BoxedError::from(self)).into_future())
    }

    /// If `self` is of type [`ErrorKind::WrongMethod`], returns the list of
    /// allowed methods.
    ///
    /// Returns `None` if `self` is a different kind of error.
    ///
    /// [`ErrorKind::WrongMethod`]: enum.ErrorKind.html#variant.WrongMethod
    pub fn allowed_methods(&self) -> Option<&[&'static http::Method]> {
        if self.kind() == ErrorKind::WrongMethod {
            Some(&self.allowed_methods)
        } else {
            None
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.source {
            None => write!(f, "{}", self.kind),
            Some(source) => write!(f, "{}: {}", self.kind, source),
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match &self.source {
            Some(source) => Some(&**source),
            None => None,
        }
    }
}

/// The different kinds of errors that can occur when using this library.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ErrorKind {
    /// Failed to parse query parameters.
    ///
    /// 400 Bad Request.
    QueryParam,
    /// Failed to deserialize the request body.
    ///
    /// 400 Bad Request.
    Body,
    /// Failed to parse path segment using `FromStr` implementation.
    ///
    /// 404 Not Found.
    PathSegment,
    /// No route matched the request URL.
    ///
    /// 404 Not Found.
    NoMatchingRoute,
    /// The invoked endpoint doesn't support this method (but does support a
    /// different one).
    ///
    /// 405 Method Not Allowed.
    WrongMethod,

    #[doc(hidden)]
    __Nonexhaustive,
}

impl ErrorKind {
    /// Returns the HTTP status code that most closely describes this error.
    pub fn http_status(&self) -> StatusCode {
        match self {
            ErrorKind::QueryParam | ErrorKind::Body => StatusCode::BAD_REQUEST,
            ErrorKind::PathSegment | ErrorKind::NoMatchingRoute => StatusCode::NOT_FOUND,
            ErrorKind::WrongMethod => StatusCode::METHOD_NOT_ALLOWED,
            ErrorKind::__Nonexhaustive => unreachable!("__Nonexhaustive must never exist"),
        }
    }
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            ErrorKind::PathSegment => "failed to parse data in path segment",
            ErrorKind::QueryParam => "failed to parse query parameters",
            ErrorKind::Body => "failed to parse request body",
            ErrorKind::NoMatchingRoute => "requested route does not exist",
            ErrorKind::WrongMethod => "method not supported on this endpoint",
            ErrorKind::__Nonexhaustive => unreachable!("__Nonexhaustive must never exist"),
        })
    }
}