Skip to main content

cert_x_gen/
error.rs

1//! Error types for CERT-X-GEN
2//!
3//! Comprehensive error handling system with context-rich error messages.
4
5use std::io;
6use std::path::PathBuf;
7use thiserror::Error;
8
9/// Result type alias for CERT-X-GEN operations
10pub type Result<T> = std::result::Result<T, Error>;
11
12/// Main error type for CERT-X-GEN
13#[derive(Error, Debug)]
14pub enum Error {
15    /// Configuration errors
16    #[error("Configuration error: {0}")]
17    Config(String),
18
19    /// Template errors
20    #[error("Template error in {template}: {message}")]
21    Template {
22        /// Template ID or path
23        template: String,
24        /// Error message
25        message: String,
26    },
27
28    /// Template not found
29    #[error("Template not found: {0}")]
30    TemplateNotFound(String),
31
32    /// Template validation failed
33    #[error("Template validation failed for {template}: {reason}")]
34    TemplateValidation {
35        /// Template ID
36        template: String,
37        /// Validation failure reason
38        reason: String,
39    },
40
41    /// Template execution error
42    #[error("Template execution failed: {0}")]
43    TemplateExecution(String),
44
45    /// Template compilation error
46    #[error("Template compilation failed for {template}: {error}")]
47    TemplateCompilation {
48        /// Template path
49        template: PathBuf,
50        /// Compilation error
51        error: String,
52    },
53
54    /// Network errors
55    #[error("Network error: {0}")]
56    Network(String),
57
58    /// HTTP request error
59    #[error("HTTP request failed: {0}")]
60    HttpRequest(#[from] reqwest::Error),
61
62    /// Target errors
63    #[error("Invalid target: {target} - {reason}")]
64    InvalidTarget {
65        /// Target specification
66        target: String,
67        /// Reason for invalidity
68        reason: String,
69    },
70
71    /// Target unreachable
72    #[error("Target unreachable: {0}")]
73    TargetUnreachable(String),
74
75    /// Parsing errors
76    #[error("Parse error: {0}")]
77    Parse(String),
78
79    /// YAML parsing error
80    #[error("YAML parse error: {0}")]
81    YamlParse(#[from] serde_yaml::Error),
82
83    /// JSON parsing error
84    #[error("JSON parse error: {0}")]
85    JsonParse(#[from] serde_json::Error),
86
87    /// IO errors
88    #[error("IO error: {0}")]
89    Io(#[from] io::Error),
90
91    /// File not found
92    #[error("File not found: {0}")]
93    FileNotFound(PathBuf),
94
95    /// Plugin errors
96    #[error("Plugin error in {plugin}: {message}")]
97    Plugin {
98        /// Plugin name
99        plugin: String,
100        /// Error message
101        message: String,
102    },
103
104    /// Plugin not found
105    #[error("Plugin not found: {0}")]
106    PluginNotFound(String),
107
108    /// Scheduler errors
109    #[error("Scheduler error: {0}")]
110    Scheduler(String),
111
112    /// Timeout error
113    #[error("Operation timed out after {duration}")]
114    Timeout {
115        /// Timeout duration
116        duration: String,
117    },
118
119    /// Execution errors
120    #[error("Execution error: {0}")]
121    Execution(String),
122
123    /// Command execution error
124    #[error("Command execution error: {0}")]
125    Command(String),
126
127    /// Rate limit exceeded
128    #[error("Rate limit exceeded: {0}")]
129    RateLimitExceeded(String),
130
131    /// Authentication error
132    #[error("Authentication failed: {0}")]
133    Authentication(String),
134
135    /// Authorization error
136    #[error("Authorization failed: {0}")]
137    Authorization(String),
138
139    /// Validation errors
140    #[error("Validation error: {0}")]
141    Validation(String),
142
143    /// Serialization error
144    #[error("Serialization error: {0}")]
145    Serialization(String),
146
147    /// Output format error
148    #[error("Output format error: {format} - {message}")]
149    OutputFormat {
150        /// Output format
151        format: String,
152        /// Error message
153        message: String,
154    },
155
156    /// Protocol error
157    #[error("Protocol error for {protocol}: {message}")]
158    Protocol {
159        /// Protocol name
160        protocol: String,
161        /// Error message
162        message: String,
163    },
164
165    /// DNS resolution error
166    #[error("DNS resolution failed for {hostname}: {error}")]
167    DnsResolution {
168        /// Hostname
169        hostname: String,
170        /// Error details
171        error: String,
172    },
173
174    /// TLS error
175    #[error("TLS error: {0}")]
176    Tls(String),
177
178    /// Certificate error
179    #[error("Certificate error: {0}")]
180    Certificate(String),
181
182    /// Matcher error
183    #[error("Matcher error: {0}")]
184    Matcher(String),
185
186    /// Database error
187    #[error("Database error: {0}")]
188    Database(String),
189
190    /// Cache error
191    #[error("Cache error: {0}")]
192    Cache(String),
193
194    /// Metrics error
195    #[error("Metrics error: {0}")]
196    Metrics(String),
197
198    /// Distributed system error
199    #[error("Distributed system error: {0}")]
200    Distributed(String),
201
202    /// Worker error
203    #[error("Worker {worker_id} error: {message}")]
204    Worker {
205        /// Worker ID
206        worker_id: String,
207        /// Error message
208        message: String,
209    },
210
211    /// Coordinator error
212    #[error("Coordinator error: {0}")]
213    Coordinator(String),
214
215    /// AI/LLM errors
216    #[error("AI error: {0}")]
217    Ai(String),
218
219    /// Internal error
220    #[error("Internal error: {0}")]
221    Internal(String),
222
223    /// Self-update error
224    #[error("Update failed: {0}")]
225    Update(#[from] self_update::errors::Error),
226
227    /// Not implemented
228    #[error("Not implemented: {0}")]
229    NotImplemented(String),
230
231    /// Generic error with context
232    #[error("{context}: {source}")]
233    WithContext {
234        /// Error context
235        context: String,
236        /// Source error
237        source: Box<Error>,
238    },
239
240    /// Multiple errors
241    #[error("Multiple errors occurred: {}", .0.len())]
242    Multiple(Vec<Error>),
243}
244
245// Implement From for prometheus::Error
246impl From<prometheus::Error> for Error {
247    fn from(err: prometheus::Error) -> Self {
248        Error::Metrics(err.to_string())
249    }
250}
251
252impl Error {
253    /// Add context to an error
254    pub fn context<S: Into<String>>(self, context: S) -> Self {
255        Error::WithContext {
256            context: context.into(),
257            source: Box::new(self),
258        }
259    }
260
261    /// Create a configuration error
262    pub fn config<S: Into<String>>(message: S) -> Self {
263        Error::Config(message.into())
264    }
265
266    /// Create a template error
267    pub fn template<S: Into<String>, M: Into<String>>(template: S, message: M) -> Self {
268        Error::Template {
269            template: template.into(),
270            message: message.into(),
271        }
272    }
273
274    /// Create an invalid target error
275    pub fn invalid_target<S: Into<String>, R: Into<String>>(target: S, reason: R) -> Self {
276        Error::InvalidTarget {
277            target: target.into(),
278            reason: reason.into(),
279        }
280    }
281
282    /// Create a command execution error
283    pub fn command<S: Into<String>>(message: S) -> Self {
284        Error::Command(message.into())
285    }
286
287    /// Check if error is fatal (should stop execution)
288    pub fn is_fatal(&self) -> bool {
289        matches!(self, Error::Internal(_) | Error::Coordinator(_))
290    }
291
292    /// Check if error is retryable
293    pub fn is_retryable(&self) -> bool {
294        matches!(
295            self,
296            Error::Network(_)
297                | Error::TargetUnreachable(_)
298                | Error::Timeout { .. }
299                | Error::RateLimitExceeded(_)
300                | Error::HttpRequest(_)
301        )
302    }
303}
304
305/// Trait for adding context to results
306pub trait ResultExt<T> {
307    /// Add context to the error
308    fn context<C: Into<String>>(self, context: C) -> Result<T>;
309
310    /// Add context using a closure (only called on error)
311    fn with_context<C, F>(self, f: F) -> Result<T>
312    where
313        C: Into<String>,
314        F: FnOnce() -> C;
315}
316
317impl<T> ResultExt<T> for Result<T> {
318    fn context<C: Into<String>>(self, context: C) -> Result<T> {
319        self.map_err(|e| e.context(context))
320    }
321
322    fn with_context<C, F>(self, f: F) -> Result<T>
323    where
324        C: Into<String>,
325        F: FnOnce() -> C,
326    {
327        self.map_err(|e| e.context(f()))
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn test_error_context() {
337        let err = Error::Parse("invalid syntax".to_string());
338        let err_with_context = err.context("parsing configuration file");
339        assert!(matches!(err_with_context, Error::WithContext { .. }));
340    }
341
342    #[test]
343    fn test_error_is_retryable() {
344        assert!(Error::Network("connection reset".to_string()).is_retryable());
345        assert!(!Error::Internal("panic".to_string()).is_retryable());
346    }
347
348    #[test]
349    fn test_error_is_fatal() {
350        assert!(Error::Internal("critical failure".to_string()).is_fatal());
351        assert!(!Error::Network("timeout".to_string()).is_fatal());
352    }
353}