Skip to main content

vld_web/rama/
rejection.rs

1//! Shared rejection type for all `Vld*` extractors.
2
3use crate::common::VldHttpError;
4use rama::http::body::util::LengthLimitError;
5use rama::http::service::web::response::IntoResponse;
6use rama::http::{Response, StatusCode, header};
7
8/// Rejection returned when validation (or body parsing) fails; wraps
9/// [`VldHttpError`].
10///
11/// Converts to a JSON response via [`crate::common`] helpers:
12/// - validation / parse → **422**
13/// - payload too large → **413**
14/// - wrong `Content-Type` on [`VldJson`](crate::rama::VldJson) /
15///   [`VldForm`](crate::rama::VldForm) → **415**
16#[derive(Debug)]
17pub struct VldRejection(VldHttpError);
18
19impl VldRejection {
20    /// Create a rejection from a [`vld::error::VldError`].
21    #[must_use]
22    pub fn from_vld(error: vld::error::VldError) -> Self {
23        Self(VldHttpError::validation(error))
24    }
25
26    /// Create a rejection for a parse / transport error message.
27    #[must_use]
28    pub fn parse(message: impl Into<String>) -> Self {
29        Self(VldHttpError::parse(message))
30    }
31
32    /// Create a rejection for an oversized request body.
33    #[must_use]
34    pub fn payload_too_large() -> Self {
35        Self(VldHttpError::payload_too_large())
36    }
37
38    /// Map a body-collection error: only a length-limit error is 413,
39    /// anything else is a 422 parse error.
40    pub(crate) fn from_body_error(e: &(dyn std::error::Error + 'static)) -> Self {
41        let mut cur = Some(e);
42        while let Some(err) = cur {
43            if err.is::<LengthLimitError>() {
44                return Self::payload_too_large();
45            }
46            cur = err.source();
47        }
48        Self::parse(format!("Failed to read request body: {e}"))
49    }
50
51    /// Borrow the underlying validation error.
52    #[must_use]
53    pub fn error(&self) -> &vld::error::VldError {
54        self.0.error()
55    }
56
57    /// HTTP status of this rejection (422, 413 or 415).
58    #[must_use]
59    pub fn status(&self) -> StatusCode {
60        StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
61    }
62
63    /// JSON response body.
64    #[must_use]
65    pub fn body(&self) -> serde_json::Value {
66        self.0.body()
67    }
68}
69
70impl From<VldHttpError> for VldRejection {
71    fn from(e: VldHttpError) -> Self {
72        Self(e)
73    }
74}
75
76impl IntoResponse for VldRejection {
77    fn into_response(self) -> Response {
78        json_response(self.status(), &self.body())
79    }
80}
81
82impl std::fmt::Display for VldRejection {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        self.0.fmt(f)
85    }
86}
87
88impl std::error::Error for VldRejection {}
89
90pub(crate) fn json_response(status: StatusCode, body: &serde_json::Value) -> Response {
91    (
92        status,
93        [(header::CONTENT_TYPE, "application/json")],
94        body.to_string(),
95    )
96        .into_response()
97}