axum_core/extract/
rejection.rs

1//! Rejection response types.
2
3use crate::__composite_rejection as composite_rejection;
4use crate::__define_rejection as define_rejection;
5
6use crate::{BoxError, Error};
7
8composite_rejection! {
9    /// Rejection type for extractors that buffer the request body. Used if the
10    /// request body cannot be buffered due to an error.
11    pub enum FailedToBufferBody {
12        LengthLimitError,
13        UnknownBodyError,
14    }
15}
16
17impl FailedToBufferBody {
18    pub(crate) fn from_err<E>(err: E) -> Self
19    where
20        E: Into<BoxError>,
21    {
22        // two layers of boxes here because `with_limited_body`
23        // wraps the `http_body_util::Limited` in a `axum_core::Body`
24        // which also wraps the error type
25        let box_error = match err.into().downcast::<Error>() {
26            Ok(err) => err.into_inner(),
27            Err(err) => err,
28        };
29        let box_error = match box_error.downcast::<Error>() {
30            Ok(err) => err.into_inner(),
31            Err(err) => err,
32        };
33        match box_error.downcast::<http_body_util::LengthLimitError>() {
34            Ok(err) => Self::LengthLimitError(LengthLimitError::from_err(err)),
35            Err(err) => Self::UnknownBodyError(UnknownBodyError::from_err(err)),
36        }
37    }
38}
39
40define_rejection! {
41    #[status = PAYLOAD_TOO_LARGE]
42    #[body = "Failed to buffer the request body"]
43    /// Encountered some other error when buffering the body.
44    ///
45    /// This can  _only_ happen when you're using [`tower_http::limit::RequestBodyLimitLayer`] or
46    /// otherwise wrapping request bodies in [`http_body_util::Limited`].
47    pub struct LengthLimitError(Error);
48}
49
50define_rejection! {
51    #[status = BAD_REQUEST]
52    #[body = "Failed to buffer the request body"]
53    /// Encountered an unknown error when buffering the body.
54    pub struct UnknownBodyError(Error);
55}
56
57define_rejection! {
58    #[status = BAD_REQUEST]
59    #[body = "Request body didn't contain valid UTF-8"]
60    /// Rejection type used when buffering the request into a [`String`] if the
61    /// body doesn't contain valid UTF-8.
62    pub struct InvalidUtf8(Error);
63}
64
65composite_rejection! {
66    /// Rejection used for [`Bytes`](bytes::Bytes).
67    ///
68    /// Contains one variant for each way the [`Bytes`](bytes::Bytes) extractor
69    /// can fail.
70    pub enum BytesRejection {
71        FailedToBufferBody,
72    }
73}
74
75composite_rejection! {
76    /// Rejection used for [`String`].
77    ///
78    /// Contains one variant for each way the [`String`] extractor can fail.
79    pub enum StringRejection {
80        FailedToBufferBody,
81        InvalidUtf8,
82    }
83}