Skip to main content

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        // peel any number of `axum_core::Error` wrappers to reach the underlying source error
23        let mut box_error = err.into();
24        loop {
25            match box_error.downcast::<Error>() {
26                Ok(unwrapped) => {
27                    box_error = unwrapped.into_inner();
28                }
29                Err(err) => {
30                    box_error = err;
31                    break;
32                }
33            }
34        }
35        match box_error.downcast::<http_body_util::LengthLimitError>() {
36            Ok(err) => Self::LengthLimitError(LengthLimitError::from_err(err)),
37            Err(err) => Self::UnknownBodyError(UnknownBodyError::from_err(err)),
38        }
39    }
40}
41
42define_rejection! {
43    #[status = PAYLOAD_TOO_LARGE]
44    #[body = "Failed to buffer the request body"]
45    /// Encountered some other error when buffering the body.
46    ///
47    /// This can _only_ happen when you're using [`tower_http::limit::RequestBodyLimitLayer`] or
48    /// otherwise wrapping request bodies in [`http_body_util::Limited`].
49    pub struct LengthLimitError(Error);
50}
51
52define_rejection! {
53    #[status = BAD_REQUEST]
54    #[body = "Failed to buffer the request body"]
55    /// Encountered an unknown error when buffering the body.
56    pub struct UnknownBodyError(Error);
57}
58
59define_rejection! {
60    #[status = BAD_REQUEST]
61    #[body = "Request body didn't contain valid UTF-8"]
62    /// Rejection type used when buffering the request into a [`String`] if the
63    /// body doesn't contain valid UTF-8.
64    pub struct InvalidUtf8(Error);
65}
66
67composite_rejection! {
68    /// Rejection used for [`Bytes`](bytes::Bytes).
69    ///
70    /// Contains one variant for each way the [`Bytes`](bytes::Bytes) extractor
71    /// can fail.
72    pub enum BytesRejection {
73        FailedToBufferBody,
74    }
75}
76
77composite_rejection! {
78    /// Rejection used for [`String`].
79    ///
80    /// Contains one variant for each way the [`String`] extractor can fail.
81    pub enum StringRejection {
82        FailedToBufferBody,
83        InvalidUtf8,
84    }
85}