Skip to main content

vld/combinators/
catch_val.rs

1use serde_json::Value;
2
3use crate::error::VldError;
4use crate::schema::VldSchema;
5
6/// Wraps a schema with a fallback value returned on ANY validation error.
7///
8/// Unlike [`ZDefault`](crate::modifiers::ZDefault) which only catches null/missing,
9/// `ZCatch` catches all errors including invalid data.
10///
11/// Created via [`VldSchema::catch()`].
12pub struct ZCatch<T: VldSchema>
13where
14    T::Output: Clone,
15{
16    inner: T,
17    fallback: T::Output,
18}
19
20impl<T: VldSchema> ZCatch<T>
21where
22    T::Output: Clone,
23{
24    /// Create the schema (the same as its `vld::` constructor function).
25    pub fn new(inner: T, fallback: T::Output) -> Self {
26        Self { inner, fallback }
27    }
28
29    /// Access the inner schema.
30    pub fn inner_schema(&self) -> &T {
31        &self.inner
32    }
33}
34
35impl<T: VldSchema> VldSchema for ZCatch<T>
36where
37    T::Output: Clone,
38{
39    type Output = T::Output;
40
41    fn parse_value(&self, value: &Value) -> Result<T::Output, VldError> {
42        Ok(self
43            .inner
44            .parse_value(value)
45            .unwrap_or_else(|_| self.fallback.clone()))
46    }
47    fn parse_missing(&self) -> Result<T::Output, VldError> {
48        Ok(self
49            .inner
50            .parse_missing()
51            .unwrap_or_else(|_| self.fallback.clone()))
52    }
53    fn output_json(&self, o: &Self::Output) -> Option<Value> {
54        self.inner.output_json(o)
55    }
56}