Skip to main content

vtcode_commons/
errors.rs

1use std::borrow::Cow;
2use std::fmt;
3
4use anyhow::{Error, Result};
5
6// File operation errors
7pub const ERR_READ_FILE: &str = "failed to read file";
8pub const ERR_WRITE_FILE: &str = "failed to write file";
9pub const ERR_READ_DIR: &str = "failed to read directory";
10pub const ERR_CREATE_DIR: &str = "failed to create directory";
11pub const ERR_REMOVE_FILE: &str = "failed to remove file";
12pub const ERR_REMOVE_DIR: &str = "failed to remove directory";
13pub const ERR_READ_DIR_ENTRY: &str = "failed to read directory entry";
14pub const ERR_GET_FILE_TYPE: &str = "failed to read file type";
15pub const ERR_GET_METADATA: &str = "failed to read file metadata";
16pub const ERR_CANONICALIZE_PATH: &str = "failed to canonicalize path";
17pub const ERR_READ_SYMLINK: &str = "failed to read symlink";
18
19// Skill/Tool errors
20pub const ERR_CREATE_SKILLS_DIR: &str = "failed to create skills directory";
21pub const ERR_CREATE_SKILL_DIR: &str = "failed to create skill directory";
22pub const ERR_READ_SKILL_CODE: &str = "failed to read skill code";
23pub const ERR_WRITE_SKILL_CODE: &str = "failed to write skill code";
24pub const ERR_READ_SKILL_METADATA: &str = "failed to read skill metadata";
25pub const ERR_WRITE_SKILL_METADATA: &str = "failed to write skill metadata";
26pub const ERR_PARSE_SKILL_METADATA: &str = "failed to parse skill metadata";
27pub const ERR_WRITE_SKILL_DOCS: &str = "failed to write skill documentation";
28pub const ERR_DELETE_SKILL: &str = "failed to delete skill";
29pub const ERR_READ_SKILLS_DIR: &str = "failed to read skills directory";
30pub const ERR_TOOL_DENIED: &str = "tool denied or unavailable by policy";
31
32// Audit/Logging errors
33pub const ERR_CREATE_AUDIT_DIR: &str = "Failed to create audit directory";
34pub const ERR_WRITE_AUDIT_LOG: &str = "failed to write audit log";
35
36// Checkpoint/Snapshot errors
37pub const ERR_CREATE_CHECKPOINT_DIR: &str = "failed to create checkpoint directory";
38pub const ERR_WRITE_CHECKPOINT: &str = "failed to write checkpoint";
39pub const ERR_READ_CHECKPOINT: &str = "failed to read checkpoint";
40
41// Policy errors
42pub const ERR_CREATE_POLICY_DIR: &str = "Failed to create directory for tool policy config";
43pub const ERR_CREATE_WORKSPACE_POLICY_DIR: &str = "Failed to create workspace policy directory";
44
45// Serialization errors
46pub const ERR_SERIALIZE_METADATA: &str = "failed to serialize skill metadata";
47pub const ERR_SERIALIZE_STATE: &str = "failed to serialize state";
48pub const ERR_DESERIALIZE: &str = "failed to deserialize data";
49
50// IPC/SDK errors
51pub const ERR_CREATE_IPC_DIR: &str = "failed to create IPC directory";
52pub const ERR_READ_REQUEST_FILE: &str = "failed to read request file";
53pub const ERR_READ_REQUEST_JSON: &str = "failed to read request JSON";
54pub const ERR_PARSE_REQUEST_JSON: &str = "failed to parse request JSON";
55pub const ERR_PARSE_ARGS: &str = "failed to parse tokenized args";
56pub const ERR_PARSE_RESULT: &str = "failed to parse de-tokenized result";
57
58/// Helper macro for file operation errors with context
59/// Usage: file_err!("path", "read") -> "failed to read path"
60#[macro_export]
61macro_rules! file_err {
62    ($path:expr, read) => {
63        format!("failed to read {}", $path)
64    };
65    ($path:expr, write) => {
66        format!("failed to write {}", $path)
67    };
68    ($path:expr, delete) => {
69        format!("failed to delete {}", $path)
70    };
71    ($path:expr, create) => {
72        format!("failed to create {}", $path)
73    };
74}
75
76/// Helper macro for context errors
77/// Usage: ctx_err!(operation, context) -> "operation context"
78#[macro_export]
79macro_rules! ctx_err {
80    ($op:expr, $ctx:expr) => {
81        format!("{}: {}", $op, $ctx)
82    };
83}
84
85/// Formats an error into a user-facing description. This allows extracted
86/// components to present consistent error messaging without depending on the
87/// CLI presentation layer.
88pub trait ErrorFormatter: Send + Sync {
89    /// Render the error into a user-facing string.
90    fn format_error(&self, error: &Error) -> Cow<'_, str>;
91}
92
93/// Reports non-fatal errors to an observability backend.
94pub trait ErrorReporter: Send + Sync {
95    /// Capture the provided error for later inspection.
96    fn capture(&self, error: &Error) -> Result<()>;
97
98    /// Convenience helper to capture a simple message.
99    fn capture_message(&self, message: impl Into<Cow<'static, str>>) -> Result<()> {
100        let message: Cow<'static, str> = message.into();
101        self.capture(&Error::msg(message))
102    }
103}
104
105/// Error reporting implementation that drops every event. Useful for tests or
106/// when a consumer does not yet integrate with error monitoring.
107#[derive(Debug, Default, Clone, Copy)]
108pub struct NoopErrorReporter;
109
110impl ErrorReporter for NoopErrorReporter {
111    fn capture(&self, _error: &Error) -> Result<()> {
112        Ok(())
113    }
114}
115
116/// Default formatter that surfaces the error's display output.
117#[derive(Debug, Default, Clone, Copy)]
118pub struct DisplayErrorFormatter;
119
120impl ErrorFormatter for DisplayErrorFormatter {
121    fn format_error(&self, error: &Error) -> Cow<'_, str> {
122        Cow::Owned(format!("{error}"))
123    }
124}
125
126/// A collection of errors that enables continuing work while collecting failures.
127///
128/// This type implements the "error parameter" pattern: instead of short-circuiting
129/// on the first error, processing continues and errors are accumulated. The caller
130/// can inspect the collection afterward to determine whether all operations
131/// succeeded.
132///
133/// # Ergonomic Result handling
134///
135/// [`collect_result`](MultiErrors::collect_result) lets you process a `Result<T, E>`
136/// while keeping the happy path dominant:
137///
138/// ```rust
139/// use vtcode_commons::MultiErrors;
140/// let mut errors: MultiErrors<String> = MultiErrors::new();
141/// let value: Option<i32> = errors.collect_result("42".parse::<i32>().map_err(|e| e.to_string()));
142/// assert_eq!(value, Some(42));
143/// ```
144///
145/// # Composing with traditional error handling
146///
147/// Use [`ok`](MultiErrors::ok) or [`to_anyhow`](MultiErrors::to_anyhow) to convert
148/// back into a traditional `Result`.
149#[derive(Debug, Clone)]
150pub struct MultiErrors<E = Error> {
151    errors: Vec<E>,
152}
153
154impl<E> MultiErrors<E> {
155    /// Create an empty error collection.
156    pub fn new() -> Self {
157        Self { errors: Vec::new() }
158    }
159
160    /// Add a single error to the collection.
161    pub fn push(&mut self, error: E) {
162        self.errors.push(error);
163    }
164
165    /// Extend the collection with multiple errors.
166    pub fn extend(&mut self, iter: impl IntoIterator<Item = E>) {
167        self.errors.extend(iter);
168    }
169
170    /// Returns `true` if no errors have been collected.
171    #[must_use]
172    pub fn is_empty(&self) -> bool {
173        self.errors.is_empty()
174    }
175
176    /// Returns the number of collected errors.
177    #[must_use]
178    pub fn len(&self) -> usize {
179        self.errors.len()
180    }
181
182    /// Consume the collector and return the underlying error vector.
183    #[must_use]
184    pub fn into_inner(self) -> Vec<E> {
185        self.errors
186    }
187
188    /// Returns a slice of all collected errors.
189    #[must_use]
190    pub fn as_slice(&self) -> &[E] {
191        &self.errors
192    }
193
194    /// Returns an iterator over the collected errors.
195    pub fn iter(&self) -> std::slice::Iter<'_, E> {
196        self.errors.iter()
197    }
198
199    /// Convert into `Result<()>` — succeeds if no errors were collected.
200    pub fn ok(self) -> std::result::Result<(), Self> {
201        if self.errors.is_empty() { Ok(()) } else { Err(self) }
202    }
203
204    /// Remove all errors from the collection.
205    pub fn clear(&mut self) {
206        self.errors.clear();
207    }
208
209    /// Process a `Result`, returning the success value or collecting the error.
210    ///
211    /// This is the key ergonomic method — it keeps the happy path as the primary
212    /// flow while silently collecting errors for later inspection.
213    pub fn collect_result<T, F>(&mut self, result: std::result::Result<T, F>) -> Option<T>
214    where
215        F: Into<E>,
216    {
217        match result {
218            Ok(val) => Some(val),
219            Err(e) => {
220                self.errors.push(e.into());
221                None
222            }
223        }
224    }
225
226    /// Convert into an [`anyhow::Error`] for use with traditional error handling.
227    #[must_use]
228    pub fn to_anyhow(&self) -> Error
229    where
230        E: fmt::Display,
231    {
232        Error::msg(self.to_string())
233    }
234}
235
236impl<E> Default for MultiErrors<E> {
237    fn default() -> Self {
238        Self::new()
239    }
240}
241
242impl<E> From<Vec<E>> for MultiErrors<E> {
243    fn from(errors: Vec<E>) -> Self {
244        Self { errors }
245    }
246}
247
248impl<E> IntoIterator for MultiErrors<E> {
249    type Item = E;
250    type IntoIter = std::vec::IntoIter<E>;
251
252    fn into_iter(self) -> Self::IntoIter {
253        self.errors.into_iter()
254    }
255}
256
257impl<E: serde::Serialize> serde::Serialize for MultiErrors<E> {
258    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
259        self.errors.serialize(serializer)
260    }
261}
262
263impl<'de, E: serde::Deserialize<'de>> serde::Deserialize<'de> for MultiErrors<E> {
264    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
265        Vec::<E>::deserialize(deserializer).map(|errors| Self { errors })
266    }
267}
268
269impl<E: fmt::Display> fmt::Display for MultiErrors<E> {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        match self.errors.len() {
272            0 => write!(f, "no errors"),
273            1 => write!(f, "{}", self.errors[0]),
274            _ => {
275                for (i, error) in self.errors.iter().enumerate() {
276                    if i > 0 {
277                        writeln!(f)?;
278                    }
279                    write!(f, "  {}. {error}", i + 1)?;
280                }
281                Ok(())
282            }
283        }
284    }
285}
286
287impl<E: std::error::Error + 'static> std::error::Error for MultiErrors<E> {
288    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
289        self.errors.first().map(|e| e as &(dyn std::error::Error + 'static))
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn formatter_uses_display() {
299        let formatter = DisplayErrorFormatter;
300        let error = Error::msg("test error");
301        assert_eq!(formatter.format_error(&error), "test error");
302    }
303
304    #[test]
305    fn noop_reporter_drops_errors() {
306        let reporter = NoopErrorReporter;
307        let error = Error::msg("test");
308        assert!(reporter.capture(&error).is_ok());
309        assert!(reporter.capture_message("message").is_ok());
310    }
311
312    #[test]
313    fn multi_errors_new_is_empty() {
314        let errors: MultiErrors<String> = MultiErrors::new();
315        assert!(errors.is_empty());
316        assert_eq!(errors.len(), 0);
317    }
318
319    #[test]
320    fn multi_errors_push_and_len() {
321        let mut errors = MultiErrors::new();
322        errors.push("error 1".to_string());
323        errors.push("error 2".to_string());
324        assert!(!errors.is_empty());
325        assert_eq!(errors.len(), 2);
326    }
327
328    #[test]
329    fn multi_errors_collect_result_ok() {
330        let mut errors: MultiErrors<String> = MultiErrors::new();
331        let value: i32 = errors.collect_result(Ok::<_, String>(42)).unwrap_or(0);
332        assert_eq!(value, 42);
333        assert!(errors.is_empty());
334    }
335
336    #[test]
337    fn multi_errors_collect_result_err() {
338        let mut errors: MultiErrors<String> = MultiErrors::new();
339        let value: i32 = errors.collect_result(Err::<i32, String>("bad".to_string())).unwrap_or(0);
340        assert_eq!(value, 0);
341        assert_eq!(errors.len(), 1);
342    }
343
344    #[test]
345    fn multi_errors_ok_succeeds_when_empty() {
346        let errors: MultiErrors<String> = MultiErrors::new();
347        assert!(errors.ok().is_ok());
348    }
349
350    #[test]
351    fn multi_errors_ok_fails_when_not_empty() {
352        let mut errors = MultiErrors::new();
353        errors.push("error".to_string());
354        assert!(errors.ok().is_err());
355    }
356
357    #[test]
358    fn multi_errors_display_empty() {
359        let errors: MultiErrors<String> = MultiErrors::new();
360        assert_eq!(errors.to_string(), "no errors");
361    }
362
363    #[test]
364    fn multi_errors_display_single() {
365        let mut errors = MultiErrors::new();
366        errors.push("something failed".to_string());
367        assert_eq!(errors.to_string(), "something failed");
368    }
369
370    #[test]
371    fn multi_errors_display_multiple() {
372        let mut errors = MultiErrors::new();
373        errors.push("first issue".to_string());
374        errors.push("second issue".to_string());
375        let display = errors.to_string();
376        assert!(display.contains("1. first issue"));
377        assert!(display.contains("2. second issue"));
378    }
379
380    #[test]
381    fn multi_errors_extend() {
382        let mut errors = MultiErrors::new();
383        errors.extend(vec!["a".to_string(), "b".to_string()]);
384        assert_eq!(errors.len(), 2);
385    }
386
387    #[test]
388    fn multi_errors_into_inner() {
389        let mut errors = MultiErrors::new();
390        errors.push("test".to_string());
391        let inner: Vec<String> = errors.into_inner();
392        assert_eq!(inner.len(), 1);
393    }
394
395    #[test]
396    fn multi_errors_from_vec() {
397        let errors: MultiErrors<String> = MultiErrors::from(vec!["a".to_string()]);
398        assert_eq!(errors.len(), 1);
399    }
400
401    #[test]
402    fn multi_errors_into_iterator() {
403        let mut errors = MultiErrors::new();
404        errors.push("a".to_string());
405        errors.push("b".to_string());
406        let collected: Vec<String> = errors.into_iter().collect();
407        assert_eq!(collected, vec!["a", "b"]);
408    }
409
410    #[test]
411    fn multi_errors_slice_access() {
412        let mut errors = MultiErrors::new();
413        errors.push("err".to_string());
414        assert_eq!(errors.as_slice(), &["err".to_string()]);
415    }
416
417    #[test]
418    fn multi_errors_to_anyhow() {
419        let mut errors = MultiErrors::new();
420        errors.push("something broke".to_string());
421        let err = errors.to_anyhow();
422        assert!(err.to_string().contains("something broke"));
423    }
424}