Skip to main content

error_forge/
error.rs

1use std::backtrace::Backtrace;
2use std::error::Error as StdError;
3use std::fmt;
4use std::io;
5use std::path::PathBuf;
6
7#[cfg(feature = "serde")]
8use serde::Serialize;
9
10/// Type alias for `error-forge` results using [`AppError`] as the
11/// error variant.
12///
13/// Prefer this over the historical [`Result`] alias — the
14/// `AppResult` name does not shadow [`std::result::Result`] in
15/// `use error_forge::*` glob imports.
16pub type AppResult<T> = std::result::Result<T, crate::error::AppError>;
17
18/// Historical alias for [`AppResult`].
19///
20/// **Deprecated since `1.0.0`** — the unqualified `Result` name
21/// shadows [`std::result::Result`] in `use error_forge::*` glob
22/// imports, which is a quiet footgun in caller code. Use
23/// [`AppResult`] instead.
24#[deprecated(
25    since = "1.0.0",
26    note = "use `error_forge::AppResult` instead — the unqualified `Result` \
27            name shadows `std::result::Result` in glob imports"
28)]
29pub type Result<T> = AppResult<T>;
30
31/// Base trait for all custom error variants.
32pub trait ForgeError: std::error::Error + Send + Sync + 'static {
33    /// Returns the kind of error, typically matching the enum variant
34    fn kind(&self) -> &'static str;
35
36    /// Returns a human-readable caption for the error
37    fn caption(&self) -> &'static str;
38
39    /// Returns true if the operation can be retried
40    fn is_retryable(&self) -> bool {
41        false
42    }
43
44    /// Returns true if the error is fatal and should terminate the program
45    fn is_fatal(&self) -> bool {
46        false
47    }
48
49    /// Returns an appropriate HTTP status code for the error
50    fn status_code(&self) -> u16 {
51        500
52    }
53
54    /// Returns an appropriate process exit code for the error
55    fn exit_code(&self) -> i32 {
56        1
57    }
58
59    /// Returns a message that is safe to show to end users.
60    ///
61    /// The default is the error's [`caption`](Self::caption): fixed
62    /// text per kind that never carries the error's data. `Display`,
63    /// [`dev_message`](Self::dev_message) and `Debug` do carry it (file
64    /// paths, endpoints with any credentials in them, source errors,
65    /// field values), so keep those for logs. Override this method to
66    /// show a message you have checked is safe, such as a validation
67    /// hint.
68    ///
69    /// Until 1.1.0 the default was the full `Display` text, which is
70    /// not safe to show.
71    ///
72    /// # Example
73    ///
74    /// ```
75    /// use error_forge::{AppError, ForgeError};
76    ///
77    /// let error = AppError::network("https://user:secret@db.internal/prod", None);
78    /// assert!(!error.user_message().contains("secret"));
79    /// assert!(error.to_string().contains("db.internal"));
80    /// ```
81    fn user_message(&self) -> String {
82        self.caption().to_string()
83    }
84
85    /// Returns a detailed technical message for developers/logs
86    fn dev_message(&self) -> String {
87        format!("[{}] {}", self.kind(), self)
88    }
89
90    /// Returns a backtrace if available
91    fn backtrace(&self) -> Option<&Backtrace> {
92        None
93    }
94
95    /// Fires the registered error hook (see
96    /// [`try_register_error_hook`](crate::macros::try_register_error_hook))
97    /// with this error's caption, kind and flags.
98    ///
99    /// Despite the name, nothing is stored: this does not touch the
100    /// error-code [`ErrorRegistry`](crate::registry::ErrorRegistry).
101    /// `AppError` and `define_errors!` constructors already fire the
102    /// hook, so calling `register` on such an error fires it a second
103    /// time. It is a no-op when no hook is registered.
104    ///
105    /// # Example
106    ///
107    /// ```
108    /// use error_forge::{AppError, ForgeError};
109    ///
110    /// let error = AppError::config("missing key");
111    /// // Reports the error to the hook again, if one is installed.
112    /// error.register();
113    /// ```
114    fn register(&self) {
115        crate::macros::call_error_hook(
116            self.caption(),
117            self.kind(),
118            self.is_fatal(),
119            self.is_retryable(),
120        );
121    }
122}
123
124/// Example error enum that can be replaced by the define_errors! macro.
125#[derive(Debug)]
126#[cfg_attr(feature = "serde", derive(Serialize))]
127pub enum AppError {
128    /// Configuration-related errors
129    Config {
130        message: String,
131        retryable: bool,
132        fatal: bool,
133        status: u16,
134    },
135
136    /// Filesystem-related errors with optional path and source error
137    Filesystem {
138        path: Option<PathBuf>,
139        #[cfg_attr(feature = "serde", serde(skip))]
140        source: io::Error,
141        retryable: bool,
142        fatal: bool,
143        status: u16,
144    },
145
146    /// Network-related errors
147    Network {
148        endpoint: String,
149        #[cfg_attr(feature = "serde", serde(skip))]
150        source: Option<Box<dyn StdError + Send + Sync>>,
151        retryable: bool,
152        fatal: bool,
153        status: u16,
154    },
155
156    /// Generic errors for anything not covered by specific variants
157    Other {
158        message: String,
159        retryable: bool,
160        fatal: bool,
161        status: u16,
162    },
163}
164
165impl std::fmt::Display for AppError {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        match self {
168            Self::Config { message, .. } => write!(f, "⚙️ Configuration Error: {message}"),
169            Self::Filesystem { path, source, .. } => {
170                if let Some(p) = path {
171                    write!(f, "💾 Filesystem Error at {p:?}: {source}")
172                } else {
173                    write!(f, "💾 Filesystem Error: {source}")
174                }
175            }
176            Self::Network {
177                endpoint, source, ..
178            } => {
179                if let Some(src) = source {
180                    write!(f, "🌐 Network Error on {endpoint}: {src}")
181                } else {
182                    write!(f, "🌐 Network Error on {endpoint}")
183                }
184            }
185            Self::Other { message, .. } => write!(f, "🚨 Error: {message}"),
186        }
187    }
188}
189
190impl std::error::Error for AppError {
191    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
192        match self {
193            AppError::Filesystem { source, .. } => Some(source),
194            AppError::Network {
195                source: Some(src), ..
196            } => Some(src.as_ref()),
197            _ => None,
198        }
199    }
200}
201
202impl From<io::Error> for AppError {
203    fn from(e: io::Error) -> Self {
204        AppError::Filesystem {
205            path: None,
206            source: e,
207            retryable: false,
208            fatal: true,
209            status: 500,
210        }
211    }
212}
213
214impl ForgeError for AppError {
215    fn kind(&self) -> &'static str {
216        match self {
217            Self::Config { .. } => "Config",
218            Self::Filesystem { .. } => "Filesystem",
219            Self::Network { .. } => "Network",
220            Self::Other { .. } => "Other",
221        }
222    }
223
224    fn caption(&self) -> &'static str {
225        match self {
226            Self::Config { .. } => "⚙️ Configuration",
227            Self::Filesystem { .. } => "💾 Filesystem",
228            Self::Network { .. } => "🌐 Network",
229            Self::Other { .. } => "🚨 Error",
230        }
231    }
232
233    fn is_retryable(&self) -> bool {
234        match self {
235            Self::Config { retryable, .. } => *retryable,
236            Self::Filesystem { retryable, .. } => *retryable,
237            Self::Network { retryable, .. } => *retryable,
238            Self::Other { retryable, .. } => *retryable,
239        }
240    }
241
242    fn is_fatal(&self) -> bool {
243        match self {
244            Self::Config { fatal, .. } => *fatal,
245            Self::Filesystem { fatal, .. } => *fatal,
246            Self::Network { fatal, .. } => *fatal,
247            Self::Other { fatal, .. } => *fatal,
248        }
249    }
250
251    fn status_code(&self) -> u16 {
252        match self {
253            Self::Config { status, .. } => *status,
254            Self::Filesystem { status, .. } => *status,
255            Self::Network { status, .. } => *status,
256            Self::Other { status, .. } => *status,
257        }
258    }
259}
260
261/// Constructor methods for AppError
262impl AppError {
263    /// Create a new Config error
264    pub fn config(message: impl Into<String>) -> Self {
265        let instance = Self::Config {
266            message: message.into(),
267            retryable: false,
268            fatal: false,
269            status: 500,
270        };
271        crate::macros::call_error_hook(
272            instance.caption(),
273            instance.kind(),
274            instance.is_fatal(),
275            instance.is_retryable(),
276        );
277        instance
278    }
279
280    /// Create a new Filesystem error
281    pub fn filesystem(path: impl Into<String>, source: impl Into<Option<io::Error>>) -> Self {
282        // Convert the source parameter
283        let source = match source.into() {
284            Some(err) => err,
285            None => io::Error::other("File operation failed"),
286        };
287
288        let instance = Self::Filesystem {
289            path: Some(path.into().into()),
290            source,
291            retryable: false,
292            fatal: false,
293            status: 500,
294        };
295        crate::macros::call_error_hook(
296            instance.caption(),
297            instance.kind(),
298            instance.is_fatal(),
299            instance.is_retryable(),
300        );
301        instance
302    }
303
304    /// Create a filesystem error with specific source error
305    pub fn filesystem_with_source(path: impl Into<PathBuf>, source: io::Error) -> Self {
306        let instance = Self::Filesystem {
307            path: Some(path.into()),
308            source,
309            retryable: false,
310            fatal: false,
311            status: 500,
312        };
313        crate::macros::call_error_hook(
314            instance.caption(),
315            instance.kind(),
316            instance.is_fatal(),
317            instance.is_retryable(),
318        );
319        instance
320    }
321
322    /// Create a new Network error
323    pub fn network(
324        endpoint: impl Into<String>,
325        source: impl Into<Option<Box<dyn StdError + Send + Sync>>>,
326    ) -> Self {
327        // Convert the source parameter
328        let source = source.into();
329
330        let instance = Self::Network {
331            endpoint: endpoint.into(),
332            source,
333            retryable: true,
334            fatal: false,
335            status: 503,
336        };
337        crate::macros::call_error_hook(
338            instance.caption(),
339            instance.kind(),
340            instance.is_fatal(),
341            instance.is_retryable(),
342        );
343        instance
344    }
345
346    /// Create a network error with specific source error
347    pub fn network_with_source(
348        endpoint: impl Into<String>,
349        source: Option<Box<dyn StdError + Send + Sync>>,
350    ) -> Self {
351        let instance = Self::Network {
352            endpoint: endpoint.into(),
353            source,
354            retryable: true,
355            fatal: false,
356            status: 503,
357        };
358        crate::macros::call_error_hook(
359            instance.caption(),
360            instance.kind(),
361            instance.is_fatal(),
362            instance.is_retryable(),
363        );
364        instance
365    }
366
367    /// Create a new generic error
368    pub fn other(message: impl Into<String>) -> Self {
369        let instance = Self::Other {
370            message: message.into(),
371            retryable: false,
372            fatal: false,
373            status: 500,
374        };
375        crate::macros::call_error_hook(
376            instance.caption(),
377            instance.kind(),
378            instance.is_fatal(),
379            instance.is_retryable(),
380        );
381        instance
382    }
383
384    /// Set whether this error is retryable
385    pub fn with_retryable(mut self, retryable: bool) -> Self {
386        match &mut self {
387            Self::Config { retryable: r, .. } => *r = retryable,
388            Self::Filesystem { retryable: r, .. } => *r = retryable,
389            Self::Network { retryable: r, .. } => *r = retryable,
390            Self::Other { retryable: r, .. } => *r = retryable,
391        }
392        self
393    }
394
395    /// Set whether this error is fatal
396    pub fn with_fatal(mut self, fatal: bool) -> Self {
397        match &mut self {
398            Self::Config { fatal: f, .. } => *f = fatal,
399            Self::Filesystem { fatal: f, .. } => *f = fatal,
400            Self::Network { fatal: f, .. } => *f = fatal,
401            Self::Other { fatal: f, .. } => *f = fatal,
402        }
403        self
404    }
405
406    /// Set the HTTP status code for this error
407    pub fn with_status(mut self, status: u16) -> Self {
408        match &mut self {
409            Self::Config { status: s, .. } => *s = status,
410            Self::Filesystem { status: s, .. } => *s = status,
411            Self::Network { status: s, .. } => *s = status,
412            Self::Other { status: s, .. } => *s = status,
413        }
414        self
415    }
416
417    /// Add a code to this error
418    pub fn with_code(self, code: impl Into<String>) -> crate::registry::CodedError<Self> {
419        crate::registry::CodedError::new(self, code.into())
420    }
421
422    /// Add context to this error
423    pub fn context<C: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static>(
424        self,
425        context: C,
426    ) -> crate::context::ContextError<Self, C> {
427        crate::context::ContextError::new(self, context)
428    }
429}