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
//! Some common error types.

use std::{
    convert::Infallible,
    fmt::{self, Debug, Display, Formatter},
};

pub use crate::http::{
    header::{
        InvalidHeaderName as ErrorInvalidHeaderName, InvalidHeaderValue as ErrorInvalidHeaderValue,
    },
    method::InvalidMethod as ErrorInvalidMethod,
    status::InvalidStatusCode as ErrorInvalidStatusCode,
    uri::{InvalidUri as ErrorInvalidUri, InvalidUriParts as ErrorInvalidUriParts},
};
use crate::{
    http::{header, StatusCode},
    Body, Response,
};

macro_rules! define_error {
    ($($(#[$docs:meta])* ($name:ident, $code:ident);)*) => {
        $(
        $(#[$docs])*
        #[inline]
        pub fn $name(error: impl Into<anyhow::Error>) -> Self {
            Self {
                status: StatusCode::$code,
                error: error.into(),
            }
        }
        )*
    };
}

/// General error.
///
/// In Poem, almost all functions that may return errors return this type, so
/// you don't need to perform tedious error type conversion.
#[derive(Debug)]
pub struct Error {
    status: StatusCode,
    error: anyhow::Error,
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.status, self.error)
    }
}

impl From<Infallible> for Error {
    fn from(_: Infallible) -> Self {
        unreachable!()
    }
}

impl From<StatusCode> for Error {
    fn from(status: StatusCode) -> Self {
        Self {
            status,
            error: anyhow::anyhow!("{}", status.canonical_reason().unwrap_or("unknown")),
        }
    }
}

impl Error {
    /// Create a new error from any error.
    ///
    /// # Example
    ///
    /// ```
    /// use std::num::ParseIntError;
    ///
    /// use poem::{http::StatusCode, Error};
    ///
    /// let err = Error::new(StatusCode::BAD_REQUEST, "a".parse::<i32>().unwrap_err());
    /// assert!(err.downcast_ref::<ParseIntError>().is_some());
    /// ```
    #[inline]
    pub fn new(status: StatusCode, error: impl Into<anyhow::Error>) -> Self {
        Self {
            status,
            error: error.into(),
        }
    }

    /// Returns the associated status code.
    #[inline]
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// Attempts to downcast the error to a concrete error type.
    #[inline]
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: Display + Debug + Send + Sync + 'static,
    {
        self.error.downcast_ref::<T>()
    }

    /// Returns true if the concrete error type is the same as T.
    #[inline]
    pub fn is<T>(&self) -> bool
    where
        T: Display + Debug + Send + Sync + 'static,
    {
        self.error.is::<T>()
    }

    /// Returns true if the concrete error type is [`ErrorNotFound`].
    #[inline]
    pub fn is_not_found(&self) -> bool {
        self.is::<ErrorNotFound>()
    }

    pub(crate) fn as_response(&self) -> Response {
        Response::builder()
            .status(self.status)
            .header(header::CONTENT_TYPE, "text/plain")
            .body(Body::from_string(self.error.to_string()))
            .unwrap()
    }

    define_error!(
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::BAD_REQUEST`].
        (bad_request, BAD_REQUEST);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::UNAUTHORIZED`].
        (unauthorized, UNAUTHORIZED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::PAYMENT_REQUIRED`].
        (payment_required, PAYMENT_REQUIRED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::FORBIDDEN`].
        (forbidden, FORBIDDEN);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::NOT_FOUND`].
        (not_found, NOT_FOUND);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::METHOD_NOT_ALLOWED`].
        (method_not_allowed, METHOD_NOT_ALLOWED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::NOT_ACCEPTABLE`].
        (not_acceptable, NOT_ACCEPTABLE);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::PROXY_AUTHENTICATION_REQUIRED`].
        (proxy_authentication_required, PROXY_AUTHENTICATION_REQUIRED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::REQUEST_TIMEOUT`].
        (request_timeout, REQUEST_TIMEOUT);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::CONFLICT`].
        (conflict, CONFLICT);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::GONE`].
        (gone, GONE);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::LENGTH_REQUIRED`].
        (length_required, LENGTH_REQUIRED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::PAYLOAD_TOO_LARGE`].
        (payload_too_large, PAYLOAD_TOO_LARGE);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::URI_TOO_LONG`].
        (uri_too_long, URI_TOO_LONG);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::UNSUPPORTED_MEDIA_TYPE`].
        (unsupported_media_type, UNSUPPORTED_MEDIA_TYPE);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::RANGE_NOT_SATISFIABLE`].
        (range_not_satisfiable, RANGE_NOT_SATISFIABLE);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::IM_A_TEAPOT`].
        (im_a_teapot, IM_A_TEAPOT);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::MISDIRECTED_REQUEST`].
        (misdirected_request, MISDIRECTED_REQUEST);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::UNPROCESSABLE_ENTITY`].
        (unprocessable_entity, UNPROCESSABLE_ENTITY);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::LOCKED`].
        (locked, LOCKED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::FAILED_DEPENDENCY`].
        (failed_dependency, FAILED_DEPENDENCY);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::UPGRADE_REQUIRED`].
        (upgrade_required, UPGRADE_REQUIRED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::PRECONDITION_FAILED`].
        (precondition_failed, PRECONDITION_FAILED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::PRECONDITION_REQUIRED`].
        (precondition_required, PRECONDITION_REQUIRED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::TOO_MANY_REQUESTS`].
        (too_many_requests, TOO_MANY_REQUESTS);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE`].
        (request_header_fields_too_large, REQUEST_HEADER_FIELDS_TOO_LARGE);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS`].
        (unavailable_for_legal_reasons, UNAVAILABLE_FOR_LEGAL_REASONS);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::EXPECTATION_FAILED`].
        (expectation_failed, EXPECTATION_FAILED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::INTERNAL_SERVER_ERROR`].
        (internal_server_error, INTERNAL_SERVER_ERROR);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::NOT_IMPLEMENTED`].
        (not_implemented, NOT_IMPLEMENTED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::BAD_GATEWAY`].
        (bad_gateway, BAD_GATEWAY);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::SERVICE_UNAVAILABLE`].
        (service_unavailable, SERVICE_UNAVAILABLE);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::GATEWAY_TIMEOUT`].
        (gateway_timeout, GATEWAY_TIMEOUT);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::HTTP_VERSION_NOT_SUPPORTED`].
        (http_version_not_supported, HTTP_VERSION_NOT_SUPPORTED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::VARIANT_ALSO_NEGOTIATES`].
        (variant_also_negotiates, VARIANT_ALSO_NEGOTIATES);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::INSUFFICIENT_STORAGE`].
        (insufficient_storage, INSUFFICIENT_STORAGE);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::LOOP_DETECTED`].
        (loop_detected, LOOP_DETECTED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::NOT_EXTENDED`].
        (not_extended, NOT_EXTENDED);
        /// Wraps any error into [`Error`] and the status code is [`StatusCode::NETWORK_AUTHENTICATION_REQUIRED`].
        (network_authentication_required, NETWORK_AUTHENTICATION_REQUIRED);
    );
}

macro_rules! define_simple_errors {
    ($($(#[$docs:meta])* ($name:ident, $status:ident, $err_msg:literal);)*) => {
        $(
        $(#[$docs])*
        #[derive(Debug, Copy, Clone, Eq, PartialEq)]
        pub struct $name;

        impl Display for $name {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                write!(f, "{}", $err_msg)
            }
        }

        impl std::error::Error for $name {}

        impl From<$name> for Error {
            fn from(err: $name) -> Error {
                Error::new(StatusCode::$status, err)
            }
        }
        )*
    };
}

define_simple_errors!(
    /// This error occurs when the path does not match.
    (ErrorNotFound, BAD_REQUEST, "not found");

    /// This error occurs when the body has been taken.
    (ErrorBodyHasBeenTaken, INTERNAL_SERVER_ERROR, "the body has been taken");

    /// Only the endpoints under the router can get the path parameters, otherwise this error will occur.
    (ErrorInvalidPathParams, INTERNAL_SERVER_ERROR, "invalid path params");

    /// This error occurs when `Content-type` is not `application/x-www-form-urlencoded`.
    (ErrorInvalidFormContentType, BAD_REQUEST, "invalid form content type");

    /// This error occurs when the cookie value in the request header is illegal.
    (ErrorCookieIllegal, BAD_REQUEST, "cookie is illegal");

    /// This error occurs if there is no cookie in the request header.
    (ErrorNoCookie, BAD_REQUEST, "there is no cookie in the request header");
);

impl From<ErrorInvalidUri> for Error {
    fn from(err: ErrorInvalidUri) -> Self {
        Error::new(StatusCode::INTERNAL_SERVER_ERROR, err)
    }
}

impl From<ErrorInvalidUriParts> for Error {
    fn from(err: ErrorInvalidUriParts) -> Self {
        Error::new(StatusCode::INTERNAL_SERVER_ERROR, err)
    }
}

impl From<ErrorInvalidHeaderName> for Error {
    fn from(err: ErrorInvalidHeaderName) -> Self {
        Error::new(StatusCode::INTERNAL_SERVER_ERROR, err)
    }
}

impl From<ErrorInvalidHeaderValue> for Error {
    fn from(err: ErrorInvalidHeaderValue) -> Self {
        Error::new(StatusCode::INTERNAL_SERVER_ERROR, err)
    }
}

impl From<ErrorInvalidMethod> for Error {
    fn from(err: ErrorInvalidMethod) -> Self {
        Error::new(StatusCode::BAD_REQUEST, err)
    }
}

impl From<ErrorInvalidStatusCode> for Error {
    fn from(err: ErrorInvalidStatusCode) -> Self {
        Error::new(StatusCode::INTERNAL_SERVER_ERROR, err)
    }
}

/// A specialized Result type for Poem.
pub type Result<T, E = Error> = ::std::result::Result<T, E>;