Skip to main content

pactum_annotations/
error.rs

1use serde::{Deserialize, Serialize};
2
3/// One field (or whole-model) invariant that failed.
4///
5/// The text field is `reason` so UniFFI Kotlin exceptions never collide with
6/// `Throwable.message`.
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub struct FieldIssue {
9    /// JSON / MessagePack key, or `"body"` for a whole-object failure.
10    pub field: String,
11    /// Stable machine code (`INVALID_EMAIL`, `STRING_TOO_LONG`, …).
12    pub code: String,
13    /// Human-readable explanation.
14    pub reason: String,
15}
16
17impl FieldIssue {
18    pub fn new(
19        field: impl Into<String>,
20        code: impl Into<String>,
21        reason: impl Into<String>,
22    ) -> Self {
23        Self {
24            field: field.into(),
25            code: code.into(),
26            reason: reason.into(),
27        }
28    }
29}
30
31impl std::fmt::Display for FieldIssue {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        write!(f, "{}: {} ({})", self.field, self.reason, self.code)
34    }
35}
36
37impl std::error::Error for FieldIssue {}
38
39/// Infrastructure / host-resolver failure (distinct from domain [`FieldIssue`] validation errors).
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct HostError {
42    pub code: String,
43    pub reason: String,
44}
45
46impl HostError {
47    pub fn new(code: impl Into<String>, reason: impl Into<String>) -> Self {
48        Self {
49            code: code.into(),
50            reason: reason.into(),
51        }
52    }
53}
54
55impl std::fmt::Display for HostError {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        write!(f, "{}: {}", self.code, self.reason)
58    }
59}
60
61impl std::error::Error for HostError {}
62
63/// Failure returned by [`crate::AsyncValidate`]: either domain field issues or a host/IO failure.
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65pub enum AsyncValidationError {
66    Issues(Vec<FieldIssue>),
67    Host(HostError),
68}
69
70impl From<FieldIssue> for AsyncValidationError {
71    fn from(issue: FieldIssue) -> Self {
72        Self::Issues(vec![issue])
73    }
74}
75
76impl From<Vec<FieldIssue>> for AsyncValidationError {
77    fn from(issues: Vec<FieldIssue>) -> Self {
78        Self::Issues(issues)
79    }
80}
81
82impl From<HostError> for AsyncValidationError {
83    fn from(err: HostError) -> Self {
84        Self::Host(err)
85    }
86}
87
88impl std::fmt::Display for AsyncValidationError {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        match self {
91            Self::Issues(issues) => match issues.as_slice() {
92                [] => write!(f, "validation failed"),
93                [only] => write!(f, "{only}"),
94                [first, rest @ ..] => {
95                    write!(f, "{first}")?;
96                    for issue in rest {
97                        write!(f, "; {issue}")?;
98                    }
99                    Ok(())
100                }
101            },
102            Self::Host(err) => write!(f, "{err}"),
103        }
104    }
105}
106
107impl std::error::Error for AsyncValidationError {
108    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
109        match self {
110            Self::Issues(issues) => issues
111                .first()
112                .map(|issue| issue as &(dyn std::error::Error + 'static)),
113            Self::Host(err) => Some(err),
114        }
115    }
116}
117
118impl crate::traits::Normalize for HostError {
119    fn normalize(&mut self) {}
120}
121
122impl crate::traits::Validate for HostError {
123    fn validate_with(&self, _ctx: &crate::context::ValidationContext) -> Result<(), Vec<FieldIssue>> {
124        Ok(())
125    }
126}
127
128impl<S> crate::traits::ScopedValidate<S> for HostError {
129    fn validate_scoped_with(
130        &self,
131        _ctx: &crate::context::ValidationContext,
132    ) -> Result<(), Vec<FieldIssue>> {
133        Ok(())
134    }
135}
136
137#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
138#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
139impl<R: ?Sized + Sync, S> crate::traits::AsyncValidate<R, S> for HostError {
140    async fn validate_async_with(
141        &self,
142        _ctx: &crate::context::ValidationContext,
143        _resolver: &R,
144    ) -> Result<(), AsyncValidationError> {
145        Ok(())
146    }
147}
148
149impl crate::traits::Normalize for FieldIssue {
150    fn normalize(&mut self) {}
151}
152
153impl crate::traits::Validate for FieldIssue {
154    fn validate_with(&self, _ctx: &crate::context::ValidationContext) -> Result<(), Vec<FieldIssue>> {
155        Ok(())
156    }
157}
158
159impl<S> crate::traits::ScopedValidate<S> for FieldIssue {
160    fn validate_scoped_with(
161        &self,
162        _ctx: &crate::context::ValidationContext,
163    ) -> Result<(), Vec<FieldIssue>> {
164        Ok(())
165    }
166}
167
168#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
169#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
170impl<R: ?Sized + Sync, S> crate::traits::AsyncValidate<R, S> for FieldIssue {
171    async fn validate_async_with(
172        &self,
173        _ctx: &crate::context::ValidationContext,
174        _resolver: &R,
175    ) -> Result<(), AsyncValidationError> {
176        Ok(())
177    }
178}