Skip to main content

vlorql_core/errors/
validation.rs

1//! [`ValidationErrors`] collection, display, and the free-function `validate`.
2
3use serde::{Deserialize, Serialize};
4
5use super::vlorql_error::VlorQLError;
6
7/// A collection of validation errors returned after validating a whole request.
8///
9/// Use [`ValidationErrors::validate`] to convert an iterator of
10/// [`VlorQLError`] into `Result<(), Self>`. The vector can be
11/// inspected via [`ValidationErrors::as_slice`].
12///
13/// # Examples
14///
15/// ```
16/// use vlorql_core::errors::{VlorQLError, ValidationErrorKind, ValidationErrors};
17/// use serde_json::json;
18///
19/// let errors = ValidationErrors::new(vec![
20///     VlorQLError::validation(
21///         ValidationErrorKind::InvalidJson,
22///         json!({"response": "bad"}),
23///     ),
24/// ]);
25/// assert_eq!(errors.len(), 1);
26/// assert!(!errors.is_empty());
27/// ```
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct ValidationErrors(pub Vec<VlorQLError>);
30
31impl std::fmt::Display for ValidationErrors {
32    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        match self.0.len() {
34            0 => formatter.write_str("no validation errors"),
35            1 => {
36                let error = &self.0[0];
37                write!(
38                    formatter,
39                    "{} validation error: {}",
40                    error.error_code(),
41                    error
42                )
43            }
44            count => {
45                writeln!(
46                    formatter,
47                    "{count} validation errors occurred (codes: {}):",
48                    self.0
49                        .iter()
50                        .map(VlorQLError::error_code)
51                        .collect::<Vec<_>>()
52                        .join(", ")
53                )?;
54                for (index, error) in self.0.iter().enumerate() {
55                    writeln!(formatter, "  [{index}] {}: {error}", error.error_code())?;
56                }
57                Ok(())
58            }
59        }
60    }
61}
62
63impl std::error::Error for ValidationErrors {
64    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
65        None
66    }
67}
68
69impl ValidationErrors {
70    /// Creates an error collection from an iterator.
71    pub fn new<I>(errors: I) -> Self
72    where
73        I: IntoIterator<Item = VlorQLError>,
74    {
75        Self(errors.into_iter().collect())
76    }
77
78    /// Validates a collection of errors, returning `Ok(())` when there are none.
79    pub fn validate<I>(errors: I) -> Result<(), Self>
80    where
81        I: IntoIterator<Item = VlorQLError>,
82    {
83        let errors = Self::new(errors);
84        if errors.0.is_empty() {
85            Ok(())
86        } else {
87            Err(errors)
88        }
89    }
90
91    /// Returns the number of collected errors.
92    pub fn len(&self) -> usize {
93        self.0.len()
94    }
95
96    /// Returns whether no validation errors were collected.
97    pub fn is_empty(&self) -> bool {
98        self.0.is_empty()
99    }
100
101    /// Returns the collected errors as a slice.
102    pub fn as_slice(&self) -> &[VlorQLError] {
103        &self.0
104    }
105
106    /// Consumes the collection and returns its errors.
107    pub fn into_inner(self) -> Vec<VlorQLError> {
108        self.0
109    }
110}
111
112impl From<Vec<VlorQLError>> for ValidationErrors {
113    fn from(errors: Vec<VlorQLError>) -> Self {
114        Self(errors)
115    }
116}
117
118/// Returns `Ok(())` when the iterator contains no errors, or aggregates all errors.
119pub fn validate<I>(errors: I) -> Result<(), ValidationErrors>
120where
121    I: IntoIterator<Item = VlorQLError>,
122{
123    ValidationErrors::validate(errors)
124}