fernctl/error/
mod.rs

1//! # Error Handling for Fern Shell
2//!
3//! This module provides a comprehensive error handling system designed for both
4//! developers and end users. It follows these principles:
5//!
6//! 1. **Rich diagnostics** — Errors include source locations, suggestions, and
7//!    documentation links to help users fix problems.
8//!
9//! 2. **Severity levels** — Not all problems are equal. Warnings allow the shell
10//!    to continue while errors require user intervention.
11//!
12//! 3. **Notification-ready** — Errors implement [`Notifiable`] so they can be
13//!    displayed as desktop notifications when the notification system is available.
14//!
15//! 4. **Type-safe error codes** — Each error variant has a unique code that can
16//!    be looked up in documentation.
17//!
18//! ## Error Hierarchy
19//!
20//! ```text
21//! FernError (top-level)
22//! ├── ConfigError     — Configuration parsing and validation
23//! ├── IoError         — File system operations
24//! ├── WatchError      — File watching failures
25//! └── IpcError        — D-Bus communication errors
26//! ```
27//!
28//! ## Usage
29//!
30//! ```rust,ignore
31//! use fernctl::error::{Result, ConfigError, Severity};
32//!
33//! fn validate_color(value: &str) -> Result<Color> {
34//!     parse_hex_color(value).map_err(|_| ConfigError::InvalidColor {
35//!         value: value.to_string(),
36//!         span: None,
37//!     })
38//! }
39//! ```
40//!
41//! ## Integration with miette
42//!
43//! All error types implement [`miette::Diagnostic`], enabling rich terminal output:
44//!
45//! ```text
46//! Error: fern::config::invalid_color
47//!
48//!   × Invalid color format: #gg0000
49//!    ╭─[config.toml:5:10]
50//!  4 │ [appearance]
51//!  5 │ accent = "#gg0000"
52//!    ·          ────────── this color value
53//!    ╰────
54//!   help: Colors must be hex format: #RRGGBB or #RRGGBBAA
55//! ```
56
57mod config;
58mod notify;
59mod severity;
60
61pub use config::ConfigError;
62pub use notify::{Notifiable, Notification};
63pub use severity::Severity;
64
65use thiserror::Error;
66
67/// A specialized [`Result`] type for fernctl operations.
68///
69/// This type alias reduces boilerplate when returning errors from functions:
70///
71/// ```rust,ignore
72/// use fernctl::error::Result;
73///
74/// fn load_config(path: &Path) -> Result<Config> {
75///     // ...
76/// }
77/// ```
78///
79/// It is equivalent to `std::result::Result<T, FernError>`.
80pub type Result<T> = std::result::Result<T, FernError>;
81
82/// The top-level error type for all fernctl operations.
83///
84/// `FernError` is an enum that wraps all specific error types in the crate.
85/// It implements [`miette::Diagnostic`] for rich error reporting and
86/// [`Notifiable`] for desktop notification integration.
87///
88/// # Error Categories
89///
90/// | Variant | Description | Typical Cause |
91/// |---------|-------------|---------------|
92/// | [`Config`](FernError::Config) | Configuration errors | Invalid TOML, bad values |
93/// | [`Io`](FernError::Io) | File system errors | Missing files, permissions |
94/// | [`Watch`](FernError::Watch) | File watcher errors | System resource limits |
95/// | [`Ipc`](FernError::Ipc) | D-Bus errors | Service not running |
96///
97/// # Example
98///
99/// ```rust,ignore
100/// use fernctl::error::{FernError, Result};
101///
102/// fn process_config(path: &Path) -> Result<Theme> {
103///     let content = std::fs::read_to_string(path)
104///         .map_err(|e| FernError::Io(e.into()))?;
105///
106///     let config = parse_toml(&content)?;  // Returns ConfigError
107///     Ok(config.into_theme())
108/// }
109/// ```
110///
111/// # Downcasting
112///
113/// You can match on specific error variants:
114///
115/// ```rust,ignore
116/// match result {
117///     Err(FernError::Config(ConfigError::InvalidColor { value, .. })) => {
118///         eprintln!("Bad color: {}", value);
119///     }
120///     Err(e) => eprintln!("Other error: {}", e),
121///     Ok(theme) => { /* use theme */ }
122/// }
123/// ```
124#[derive(Debug, Error)]
125#[non_exhaustive]
126pub enum FernError {
127    /// Configuration parsing or validation error.
128    ///
129    /// This variant wraps [`ConfigError`], which provides detailed information
130    /// about what went wrong in the configuration file.
131    #[error(transparent)]
132    Config(#[from] ConfigError),
133
134    /// File system I/O error.
135    ///
136    /// Wraps standard I/O errors with additional context about what operation
137    /// was being attempted.
138    #[error("I/O error: {message}")]
139    Io {
140        /// Human-readable description of what operation failed.
141        message: String,
142        /// The underlying I/O error.
143        #[source]
144        source: std::io::Error,
145    },
146
147    /// File watcher error.
148    ///
149    /// Occurs when the file watching system fails to initialize or encounters
150    /// an error while monitoring files.
151    #[error("File watch error: {message}")]
152    Watch {
153        /// Description of what went wrong.
154        message: String,
155    },
156
157    /// Inter-process communication error.
158    ///
159    /// Occurs when communication with QuickShell via D-Bus fails.
160    #[error("IPC error: {message}")]
161    Ipc {
162        /// Description of the communication failure.
163        message: String,
164    },
165}
166
167impl FernError {
168    /// Creates an I/O error with context.
169    ///
170    /// # Arguments
171    ///
172    /// * `message` — A description of what operation was being attempted
173    /// * `source` — The underlying I/O error
174    ///
175    /// # Example
176    ///
177    /// ```rust,ignore
178    /// let result = std::fs::read_to_string(path)
179    ///     .map_err(|e| FernError::io("reading config file", e))?;
180    /// ```
181    #[must_use]
182    pub fn io(message: impl Into<String>, source: std::io::Error) -> Self {
183        Self::Io {
184            message: message.into(),
185            source,
186        }
187    }
188
189    /// Creates a file watch error.
190    ///
191    /// # Arguments
192    ///
193    /// * `message` — A description of what went wrong
194    ///
195    /// # Example
196    ///
197    /// ```rust,ignore
198    /// FernError::watch("failed to initialize file watcher")
199    /// ```
200    #[must_use]
201    pub fn watch(message: impl Into<String>) -> Self {
202        Self::Watch {
203            message: message.into(),
204        }
205    }
206
207    /// Creates an IPC error.
208    ///
209    /// # Arguments
210    ///
211    /// * `message` — A description of the communication failure
212    ///
213    /// # Example
214    ///
215    /// ```rust,ignore
216    /// FernError::ipc("QuickShell did not respond to reload signal")
217    /// ```
218    #[must_use]
219    pub fn ipc(message: impl Into<String>) -> Self {
220        Self::Ipc {
221            message: message.into(),
222        }
223    }
224
225    /// Returns the severity level of this error.
226    ///
227    /// Severity determines how the error should be handled:
228    ///
229    /// - [`Severity::Warning`] — Log and continue
230    /// - [`Severity::Error`] — Operation failed, but shell can continue
231    /// - [`Severity::Fatal`] — Shell cannot continue
232    ///
233    /// # Example
234    ///
235    /// ```rust,ignore
236    /// if error.severity().is_fatal() {
237    ///     std::process::exit(1);
238    /// }
239    /// ```
240    #[must_use]
241    pub fn severity(&self) -> Severity {
242        match self {
243            Self::Config(e) => e.severity(),
244            Self::Io { .. } => Severity::Error,
245            Self::Watch { .. } => Severity::Warning,
246            Self::Ipc { .. } => Severity::Error,
247        }
248    }
249
250    /// Returns the error code for documentation lookup.
251    ///
252    /// Error codes follow the pattern `fern::<category>::<specific>` and can
253    /// be used to find detailed documentation about the error.
254    ///
255    /// # Example
256    ///
257    /// ```rust,ignore
258    /// // Prints something like "fern::config::invalid_color"
259    /// println!("See docs for: {}", error.code());
260    /// ```
261    #[must_use]
262    pub fn code(&self) -> &'static str {
263        match self {
264            Self::Config(e) => e.code(),
265            Self::Io { .. } => "fern::io::error",
266            Self::Watch { .. } => "fern::watch::error",
267            Self::Ipc { .. } => "fern::ipc::error",
268        }
269    }
270}
271
272// Implement miette::Diagnostic manually to avoid derive macro conflicts
273impl miette::Diagnostic for FernError {
274    fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
275        Some(Box::new(FernError::code(self)))
276    }
277
278    fn severity(&self) -> Option<miette::Severity> {
279        Some(match FernError::severity(self) {
280            Severity::Info => miette::Severity::Advice,
281            Severity::Warning => miette::Severity::Warning,
282            Severity::Error => miette::Severity::Error,
283            Severity::Fatal => miette::Severity::Error,
284        })
285    }
286
287    fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
288        match self {
289            Self::Config(e) => e.help(),
290            Self::Io { .. } => Some(Box::new("Check file permissions and path")),
291            Self::Watch { .. } => Some(Box::new("Check system resource limits (inotify watches on Linux)")),
292            Self::Ipc { .. } => Some(Box::new("Ensure QuickShell is running and the D-Bus session is available")),
293        }
294    }
295
296    fn source_code(&self) -> Option<&dyn miette::SourceCode> {
297        match self {
298            Self::Config(e) => e.source_code(),
299            _ => None,
300        }
301    }
302
303    fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
304        match self {
305            Self::Config(e) => e.labels(),
306            _ => None,
307        }
308    }
309
310    fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
311        match self {
312            Self::Config(e) => Some(e),
313            _ => None,
314        }
315    }
316}
317
318impl Notifiable for FernError {
319    fn severity(&self) -> Severity {
320        FernError::severity(self)
321    }
322
323    fn title(&self) -> String {
324        match self {
325            Self::Config(e) => e.title(),
326            Self::Io { .. } => "File Error".to_string(),
327            Self::Watch { .. } => "Watch Error".to_string(),
328            Self::Ipc { .. } => "Communication Error".to_string(),
329        }
330    }
331
332    fn body(&self) -> String {
333        self.to_string()
334    }
335
336    fn suggestion(&self) -> Option<String> {
337        match self {
338            Self::Config(e) => e.suggestion(),
339            Self::Io { .. } => Some("Check file permissions and path".to_string()),
340            Self::Watch { .. } => Some("Check system resource limits".to_string()),
341            Self::Ipc { .. } => Some("Ensure QuickShell is running".to_string()),
342        }
343    }
344
345    fn code(&self) -> Option<&'static str> {
346        Some(FernError::code(self))
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    #[test]
355    fn error_is_send_sync() {
356        fn assert_send_sync<T: Send + Sync>() {}
357        assert_send_sync::<FernError>();
358    }
359
360    #[test]
361    fn io_error_has_correct_code() {
362        let err = FernError::io(
363            "test",
364            std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
365        );
366        assert_eq!(FernError::code(&err), "fern::io::error");
367    }
368}