Skip to main content

error_forge/
collector.rs

1use crate::error::ForgeError;
2use std::error::Error;
3use std::fmt;
4
5/// A collection of errors that can be accumulated and returned as a single result
6#[derive(Debug)]
7pub struct ErrorCollector<E> {
8    /// The collected errors
9    errors: Vec<E>,
10}
11
12/// An empty collector. Written by hand so `E` does not have to
13/// implement `Default`, which `#[derive(Default)]` would require.
14impl<E> Default for ErrorCollector<E> {
15    fn default() -> Self {
16        Self::new()
17    }
18}
19
20impl<E> ErrorCollector<E> {
21    /// Create a new empty error collector
22    pub fn new() -> Self {
23        Self { errors: Vec::new() }
24    }
25
26    /// Add an error to the collection
27    pub fn push(&mut self, error: E) {
28        self.errors.push(error);
29    }
30
31    /// Add an error to the collection and return self for chaining
32    pub fn with(mut self, error: E) -> Self {
33        self.push(error);
34        self
35    }
36
37    /// Check if the collection is empty
38    pub fn is_empty(&self) -> bool {
39        self.errors.is_empty()
40    }
41
42    /// Get the number of collected errors
43    pub fn len(&self) -> usize {
44        self.errors.len()
45    }
46
47    /// Return a result that is Ok if there are no errors, or Err with the collector otherwise
48    pub fn into_result<T>(self, ok_value: T) -> Result<T, Self> {
49        if self.is_empty() {
50            Ok(ok_value)
51        } else {
52            Err(self)
53        }
54    }
55
56    /// Return a result that is Ok if there are no errors, or Err with the collector otherwise
57    pub fn result<T>(&self, ok_value: T) -> Result<T, &Self> {
58        if self.is_empty() {
59            Ok(ok_value)
60        } else {
61            Err(self)
62        }
63    }
64
65    /// Consume the collector and return the vector of errors
66    pub fn into_errors(self) -> Vec<E> {
67        self.errors
68    }
69
70    /// Get a reference to the vector of errors
71    pub fn errors(&self) -> &Vec<E> {
72        &self.errors
73    }
74
75    /// Get a mutable reference to the vector of errors
76    pub fn errors_mut(&mut self) -> &mut Vec<E> {
77        &mut self.errors
78    }
79
80    /// Add all errors from another collector
81    pub fn extend(&mut self, other: ErrorCollector<E>) {
82        self.errors.extend(other.errors);
83    }
84
85    /// Try an operation that may return an error, collecting the error if it occurs
86    pub fn try_collect<F, T>(&mut self, op: F) -> Option<T>
87    where
88        F: FnOnce() -> Result<T, E>,
89    {
90        match op() {
91            Ok(val) => Some(val),
92            Err(e) => {
93                self.push(e);
94                None
95            }
96        }
97    }
98}
99
100impl<E: fmt::Display> fmt::Display for ErrorCollector<E> {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        if self.errors.is_empty() {
103            write!(f, "No errors")
104        } else if self.errors.len() == 1 {
105            write!(f, "1 error: {}", self.errors[0])
106        } else {
107            writeln!(f, "{} errors:", self.errors.len())?;
108            for (i, err) in self.errors.iter().enumerate() {
109                writeln!(f, "  {}. {}", i + 1, err)?;
110            }
111            Ok(())
112        }
113    }
114}
115
116impl<E: Error> Error for ErrorCollector<E> {
117    fn source(&self) -> Option<&(dyn Error + 'static)> {
118        self.errors.first().and_then(|e| e.source())
119    }
120}
121
122/// Extension trait for Result types to collect errors
123pub trait CollectError<T, E> {
124    /// Collect an error into an ErrorCollector if the result is an error
125    fn collect_err(self, collector: &mut ErrorCollector<E>) -> Option<T>;
126}
127
128impl<T, E> CollectError<T, E> for Result<T, E> {
129    fn collect_err(self, collector: &mut ErrorCollector<E>) -> Option<T> {
130        match self {
131            Ok(val) => Some(val),
132            Err(e) => {
133                collector.push(e);
134                None
135            }
136        }
137    }
138}
139
140// Special implementation for ForgeError types to provide rich error collection
141impl<E: ForgeError> ErrorCollector<E> {
142    /// Return a summary of the collected errors using ForgeError traits
143    pub fn summary(&self) -> String {
144        if self.errors.is_empty() {
145            return "No errors".to_string();
146        }
147
148        let mut result = String::new();
149        let fatal_count = self.errors.iter().filter(|e| e.is_fatal()).count();
150        let retryable_count = self.errors.iter().filter(|e| e.is_retryable()).count();
151
152        result.push_str(&format!(
153            "{} errors collected ({} fatal, {} retryable):\n",
154            self.errors.len(),
155            fatal_count,
156            retryable_count
157        ));
158
159        for (i, err) in self.errors.iter().enumerate() {
160            result.push_str(&format!(
161                "  {}. [{}] {}\n",
162                i + 1,
163                err.kind(),
164                err.dev_message()
165            ));
166        }
167
168        result
169    }
170
171    /// Check if any of the collected errors is marked as fatal
172    pub fn has_fatal(&self) -> bool {
173        self.errors.iter().any(|e| e.is_fatal())
174    }
175
176    /// Check if all collected errors are retryable
177    pub fn all_retryable(&self) -> bool {
178        !self.errors.is_empty() && self.errors.iter().all(|e| e.is_retryable())
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use crate::AppError;
186
187    #[test]
188    fn test_error_collector() {
189        let mut collector = ErrorCollector::new();
190
191        assert!(collector.is_empty());
192
193        collector.push(AppError::config("Config error"));
194        collector.push(AppError::filesystem("File not found", None));
195
196        assert_eq!(collector.len(), 2);
197
198        let result: Result<(), _> = collector.into_result(());
199        assert!(result.is_err());
200    }
201
202    #[test]
203    fn test_collect_error() {
204        let mut collector = ErrorCollector::new();
205
206        let result1: Result<i32, AppError> = Ok(42);
207        let result2: Result<i32, AppError> = Err(AppError::network("Connection failed", None));
208
209        let val1 = result1.collect_err(&mut collector);
210        let val2 = result2.collect_err(&mut collector);
211
212        assert_eq!(val1, Some(42));
213        assert_eq!(val2, None);
214        assert_eq!(collector.len(), 1);
215    }
216
217    #[test]
218    fn test_forge_error_collector() {
219        let mut collector = ErrorCollector::new();
220
221        collector.push(AppError::config("Config error").with_fatal(true));
222        collector.push(AppError::network("Connection failed", None).with_retryable(true));
223
224        assert!(collector.has_fatal());
225        assert!(!collector.all_retryable());
226
227        let summary = collector.summary();
228        assert!(summary.contains("2 errors collected (1 fatal, 1 retryable)"));
229        assert!(summary.contains("[Config]"));
230        assert!(summary.contains("[Network]"));
231    }
232}