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 user-facing message that can be shown to end users
60    fn user_message(&self) -> String {
61        self.to_string()
62    }
63
64    /// Returns a detailed technical message for developers/logs
65    fn dev_message(&self) -> String {
66        format!("[{}] {}", self.kind(), self)
67    }
68
69    /// Returns a backtrace if available
70    fn backtrace(&self) -> Option<&Backtrace> {
71        None
72    }
73
74    /// Fires the registered error hook (see
75    /// [`try_register_error_hook`](crate::macros::try_register_error_hook))
76    /// with this error's caption, kind and flags.
77    ///
78    /// Despite the name, nothing is stored: this does not touch the
79    /// error-code [`ErrorRegistry`](crate::registry::ErrorRegistry).
80    /// `AppError` and `define_errors!` constructors already fire the
81    /// hook, so calling `register` on such an error fires it a second
82    /// time. It is a no-op when no hook is registered.
83    ///
84    /// # Example
85    ///
86    /// ```
87    /// use error_forge::{AppError, ForgeError};
88    ///
89    /// let error = AppError::config("missing key");
90    /// // Reports the error to the hook again, if one is installed.
91    /// error.register();
92    /// ```
93    fn register(&self) {
94        crate::macros::call_error_hook(
95            self.caption(),
96            self.kind(),
97            self.is_fatal(),
98            self.is_retryable(),
99        );
100    }
101}
102
103/// Example error enum that can be replaced by the define_errors! macro.
104#[derive(Debug)]
105#[cfg_attr(feature = "serde", derive(Serialize))]
106pub enum AppError {
107    /// Configuration-related errors
108    Config {
109        message: String,
110        retryable: bool,
111        fatal: bool,
112        status: u16,
113    },
114
115    /// Filesystem-related errors with optional path and source error
116    Filesystem {
117        path: Option<PathBuf>,
118        #[cfg_attr(feature = "serde", serde(skip))]
119        source: io::Error,
120        retryable: bool,
121        fatal: bool,
122        status: u16,
123    },
124
125    /// Network-related errors
126    Network {
127        endpoint: String,
128        #[cfg_attr(feature = "serde", serde(skip))]
129        source: Option<Box<dyn StdError + Send + Sync>>,
130        retryable: bool,
131        fatal: bool,
132        status: u16,
133    },
134
135    /// Generic errors for anything not covered by specific variants
136    Other {
137        message: String,
138        retryable: bool,
139        fatal: bool,
140        status: u16,
141    },
142}
143
144impl std::fmt::Display for AppError {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        match self {
147            Self::Config { message, .. } => write!(f, "⚙️ Configuration Error: {message}"),
148            Self::Filesystem { path, source, .. } => {
149                if let Some(p) = path {
150                    write!(f, "💾 Filesystem Error at {p:?}: {source}")
151                } else {
152                    write!(f, "💾 Filesystem Error: {source}")
153                }
154            }
155            Self::Network {
156                endpoint, source, ..
157            } => {
158                if let Some(src) = source {
159                    write!(f, "🌐 Network Error on {endpoint}: {src}")
160                } else {
161                    write!(f, "🌐 Network Error on {endpoint}")
162                }
163            }
164            Self::Other { message, .. } => write!(f, "🚨 Error: {message}"),
165        }
166    }
167}
168
169impl std::error::Error for AppError {
170    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
171        match self {
172            AppError::Filesystem { source, .. } => Some(source),
173            AppError::Network {
174                source: Some(src), ..
175            } => Some(src.as_ref()),
176            _ => None,
177        }
178    }
179}
180
181impl From<io::Error> for AppError {
182    fn from(e: io::Error) -> Self {
183        AppError::Filesystem {
184            path: None,
185            source: e,
186            retryable: false,
187            fatal: true,
188            status: 500,
189        }
190    }
191}
192
193impl ForgeError for AppError {
194    fn kind(&self) -> &'static str {
195        match self {
196            Self::Config { .. } => "Config",
197            Self::Filesystem { .. } => "Filesystem",
198            Self::Network { .. } => "Network",
199            Self::Other { .. } => "Other",
200        }
201    }
202
203    fn caption(&self) -> &'static str {
204        match self {
205            Self::Config { .. } => "⚙️ Configuration",
206            Self::Filesystem { .. } => "💾 Filesystem",
207            Self::Network { .. } => "🌐 Network",
208            Self::Other { .. } => "🚨 Error",
209        }
210    }
211
212    fn is_retryable(&self) -> bool {
213        match self {
214            Self::Config { retryable, .. } => *retryable,
215            Self::Filesystem { retryable, .. } => *retryable,
216            Self::Network { retryable, .. } => *retryable,
217            Self::Other { retryable, .. } => *retryable,
218        }
219    }
220
221    fn is_fatal(&self) -> bool {
222        match self {
223            Self::Config { fatal, .. } => *fatal,
224            Self::Filesystem { fatal, .. } => *fatal,
225            Self::Network { fatal, .. } => *fatal,
226            Self::Other { fatal, .. } => *fatal,
227        }
228    }
229
230    fn status_code(&self) -> u16 {
231        match self {
232            Self::Config { status, .. } => *status,
233            Self::Filesystem { status, .. } => *status,
234            Self::Network { status, .. } => *status,
235            Self::Other { status, .. } => *status,
236        }
237    }
238}
239
240/// Constructor methods for AppError
241impl AppError {
242    /// Create a new Config error
243    pub fn config(message: impl Into<String>) -> Self {
244        let instance = Self::Config {
245            message: message.into(),
246            retryable: false,
247            fatal: false,
248            status: 500,
249        };
250        crate::macros::call_error_hook(
251            instance.caption(),
252            instance.kind(),
253            instance.is_fatal(),
254            instance.is_retryable(),
255        );
256        instance
257    }
258
259    /// Create a new Filesystem error
260    pub fn filesystem(path: impl Into<String>, source: impl Into<Option<io::Error>>) -> Self {
261        // Convert the source parameter
262        let source = match source.into() {
263            Some(err) => err,
264            None => io::Error::other("File operation failed"),
265        };
266
267        let instance = Self::Filesystem {
268            path: Some(path.into().into()),
269            source,
270            retryable: false,
271            fatal: false,
272            status: 500,
273        };
274        crate::macros::call_error_hook(
275            instance.caption(),
276            instance.kind(),
277            instance.is_fatal(),
278            instance.is_retryable(),
279        );
280        instance
281    }
282
283    /// Create a filesystem error with specific source error
284    pub fn filesystem_with_source(path: impl Into<PathBuf>, source: io::Error) -> Self {
285        let instance = Self::Filesystem {
286            path: Some(path.into()),
287            source,
288            retryable: false,
289            fatal: false,
290            status: 500,
291        };
292        crate::macros::call_error_hook(
293            instance.caption(),
294            instance.kind(),
295            instance.is_fatal(),
296            instance.is_retryable(),
297        );
298        instance
299    }
300
301    /// Create a new Network error
302    pub fn network(
303        endpoint: impl Into<String>,
304        source: impl Into<Option<Box<dyn StdError + Send + Sync>>>,
305    ) -> Self {
306        // Convert the source parameter
307        let source = source.into();
308
309        let instance = Self::Network {
310            endpoint: endpoint.into(),
311            source,
312            retryable: true,
313            fatal: false,
314            status: 503,
315        };
316        crate::macros::call_error_hook(
317            instance.caption(),
318            instance.kind(),
319            instance.is_fatal(),
320            instance.is_retryable(),
321        );
322        instance
323    }
324
325    /// Create a network error with specific source error
326    pub fn network_with_source(
327        endpoint: impl Into<String>,
328        source: Option<Box<dyn StdError + Send + Sync>>,
329    ) -> Self {
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 new generic error
347    pub fn other(message: impl Into<String>) -> Self {
348        let instance = Self::Other {
349            message: message.into(),
350            retryable: false,
351            fatal: false,
352            status: 500,
353        };
354        crate::macros::call_error_hook(
355            instance.caption(),
356            instance.kind(),
357            instance.is_fatal(),
358            instance.is_retryable(),
359        );
360        instance
361    }
362
363    /// Set whether this error is retryable
364    pub fn with_retryable(mut self, retryable: bool) -> Self {
365        match &mut self {
366            Self::Config { retryable: r, .. } => *r = retryable,
367            Self::Filesystem { retryable: r, .. } => *r = retryable,
368            Self::Network { retryable: r, .. } => *r = retryable,
369            Self::Other { retryable: r, .. } => *r = retryable,
370        }
371        self
372    }
373
374    /// Set whether this error is fatal
375    pub fn with_fatal(mut self, fatal: bool) -> Self {
376        match &mut self {
377            Self::Config { fatal: f, .. } => *f = fatal,
378            Self::Filesystem { fatal: f, .. } => *f = fatal,
379            Self::Network { fatal: f, .. } => *f = fatal,
380            Self::Other { fatal: f, .. } => *f = fatal,
381        }
382        self
383    }
384
385    /// Set the HTTP status code for this error
386    pub fn with_status(mut self, status: u16) -> Self {
387        match &mut self {
388            Self::Config { status: s, .. } => *s = status,
389            Self::Filesystem { status: s, .. } => *s = status,
390            Self::Network { status: s, .. } => *s = status,
391            Self::Other { status: s, .. } => *s = status,
392        }
393        self
394    }
395
396    /// Add a code to this error
397    pub fn with_code(self, code: impl Into<String>) -> crate::registry::CodedError<Self> {
398        crate::registry::CodedError::new(self, code.into())
399    }
400
401    /// Add context to this error
402    pub fn context<C: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static>(
403        self,
404        context: C,
405    ) -> crate::context::ContextError<Self, C> {
406        crate::context::ContextError::new(self, context)
407    }
408}