vld_web/rama/
rejection.rs1use crate::common::VldHttpError;
4use rama::http::body::util::LengthLimitError;
5use rama::http::service::web::response::IntoResponse;
6use rama::http::{Response, StatusCode, header};
7
8#[derive(Debug)]
17pub struct VldRejection(VldHttpError);
18
19impl VldRejection {
20 #[must_use]
22 pub fn from_vld(error: vld::error::VldError) -> Self {
23 Self(VldHttpError::validation(error))
24 }
25
26 #[must_use]
28 pub fn parse(message: impl Into<String>) -> Self {
29 Self(VldHttpError::parse(message))
30 }
31
32 #[must_use]
34 pub fn payload_too_large() -> Self {
35 Self(VldHttpError::payload_too_large())
36 }
37
38 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 #[must_use]
53 pub fn error(&self) -> &vld::error::VldError {
54 self.0.error()
55 }
56
57 #[must_use]
59 pub fn status(&self) -> StatusCode {
60 StatusCode::from_u16(self.0.status()).unwrap_or(StatusCode::UNPROCESSABLE_ENTITY)
61 }
62
63 #[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}