error-forge 1.1.0

Pragmatic Rust error-handling framework with stable error metadata, contextual diagnostics, optional async support, and synchronous recovery primitives (retry, circuit-breaker, backoff). Optional #[derive(ModError)], declarative define_errors!, and feature-gated logging / tracing / serde adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use std::backtrace::Backtrace;
use std::error::Error as StdError;
use std::fmt;
use std::io;
use std::path::PathBuf;

#[cfg(feature = "serde")]
use serde::Serialize;

/// Type alias for `error-forge` results using [`AppError`] as the
/// error variant.
///
/// Prefer this over the historical [`Result`] alias — the
/// `AppResult` name does not shadow [`std::result::Result`] in
/// `use error_forge::*` glob imports.
pub type AppResult<T> = std::result::Result<T, crate::error::AppError>;

/// Historical alias for [`AppResult`].
///
/// **Deprecated since `1.0.0`** — the unqualified `Result` name
/// shadows [`std::result::Result`] in `use error_forge::*` glob
/// imports, which is a quiet footgun in caller code. Use
/// [`AppResult`] instead.
#[deprecated(
    since = "1.0.0",
    note = "use `error_forge::AppResult` instead — the unqualified `Result` \
            name shadows `std::result::Result` in glob imports"
)]
pub type Result<T> = AppResult<T>;

/// Base trait for all custom error variants.
pub trait ForgeError: std::error::Error + Send + Sync + 'static {
    /// Returns the kind of error, typically matching the enum variant
    fn kind(&self) -> &'static str;

    /// Returns a human-readable caption for the error
    fn caption(&self) -> &'static str;

    /// Returns true if the operation can be retried
    fn is_retryable(&self) -> bool {
        false
    }

    /// Returns true if the error is fatal and should terminate the program
    fn is_fatal(&self) -> bool {
        false
    }

    /// Returns an appropriate HTTP status code for the error
    fn status_code(&self) -> u16 {
        500
    }

    /// Returns an appropriate process exit code for the error
    fn exit_code(&self) -> i32 {
        1
    }

    /// Returns a user-facing message that can be shown to end users
    fn user_message(&self) -> String {
        self.to_string()
    }

    /// Returns a detailed technical message for developers/logs
    fn dev_message(&self) -> String {
        format!("[{}] {}", self.kind(), self)
    }

    /// Returns a backtrace if available
    fn backtrace(&self) -> Option<&Backtrace> {
        None
    }

    /// Fires the registered error hook (see
    /// [`try_register_error_hook`](crate::macros::try_register_error_hook))
    /// with this error's caption, kind and flags.
    ///
    /// Despite the name, nothing is stored: this does not touch the
    /// error-code [`ErrorRegistry`](crate::registry::ErrorRegistry).
    /// `AppError` and `define_errors!` constructors already fire the
    /// hook, so calling `register` on such an error fires it a second
    /// time. It is a no-op when no hook is registered.
    ///
    /// # Example
    ///
    /// ```
    /// use error_forge::{AppError, ForgeError};
    ///
    /// let error = AppError::config("missing key");
    /// // Reports the error to the hook again, if one is installed.
    /// error.register();
    /// ```
    fn register(&self) {
        crate::macros::call_error_hook(
            self.caption(),
            self.kind(),
            self.is_fatal(),
            self.is_retryable(),
        );
    }
}

/// Example error enum that can be replaced by the define_errors! macro.
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub enum AppError {
    /// Configuration-related errors
    Config {
        message: String,
        retryable: bool,
        fatal: bool,
        status: u16,
    },

    /// Filesystem-related errors with optional path and source error
    Filesystem {
        path: Option<PathBuf>,
        #[cfg_attr(feature = "serde", serde(skip))]
        source: io::Error,
        retryable: bool,
        fatal: bool,
        status: u16,
    },

    /// Network-related errors
    Network {
        endpoint: String,
        #[cfg_attr(feature = "serde", serde(skip))]
        source: Option<Box<dyn StdError + Send + Sync>>,
        retryable: bool,
        fatal: bool,
        status: u16,
    },

    /// Generic errors for anything not covered by specific variants
    Other {
        message: String,
        retryable: bool,
        fatal: bool,
        status: u16,
    },
}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Config { message, .. } => write!(f, "⚙️ Configuration Error: {message}"),
            Self::Filesystem { path, source, .. } => {
                if let Some(p) = path {
                    write!(f, "💾 Filesystem Error at {p:?}: {source}")
                } else {
                    write!(f, "💾 Filesystem Error: {source}")
                }
            }
            Self::Network {
                endpoint, source, ..
            } => {
                if let Some(src) = source {
                    write!(f, "🌐 Network Error on {endpoint}: {src}")
                } else {
                    write!(f, "🌐 Network Error on {endpoint}")
                }
            }
            Self::Other { message, .. } => write!(f, "🚨 Error: {message}"),
        }
    }
}

impl std::error::Error for AppError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            AppError::Filesystem { source, .. } => Some(source),
            AppError::Network {
                source: Some(src), ..
            } => Some(src.as_ref()),
            _ => None,
        }
    }
}

impl From<io::Error> for AppError {
    fn from(e: io::Error) -> Self {
        AppError::Filesystem {
            path: None,
            source: e,
            retryable: false,
            fatal: true,
            status: 500,
        }
    }
}

impl ForgeError for AppError {
    fn kind(&self) -> &'static str {
        match self {
            Self::Config { .. } => "Config",
            Self::Filesystem { .. } => "Filesystem",
            Self::Network { .. } => "Network",
            Self::Other { .. } => "Other",
        }
    }

    fn caption(&self) -> &'static str {
        match self {
            Self::Config { .. } => "⚙️ Configuration",
            Self::Filesystem { .. } => "💾 Filesystem",
            Self::Network { .. } => "🌐 Network",
            Self::Other { .. } => "🚨 Error",
        }
    }

    fn is_retryable(&self) -> bool {
        match self {
            Self::Config { retryable, .. } => *retryable,
            Self::Filesystem { retryable, .. } => *retryable,
            Self::Network { retryable, .. } => *retryable,
            Self::Other { retryable, .. } => *retryable,
        }
    }

    fn is_fatal(&self) -> bool {
        match self {
            Self::Config { fatal, .. } => *fatal,
            Self::Filesystem { fatal, .. } => *fatal,
            Self::Network { fatal, .. } => *fatal,
            Self::Other { fatal, .. } => *fatal,
        }
    }

    fn status_code(&self) -> u16 {
        match self {
            Self::Config { status, .. } => *status,
            Self::Filesystem { status, .. } => *status,
            Self::Network { status, .. } => *status,
            Self::Other { status, .. } => *status,
        }
    }
}

/// Constructor methods for AppError
impl AppError {
    /// Create a new Config error
    pub fn config(message: impl Into<String>) -> Self {
        let instance = Self::Config {
            message: message.into(),
            retryable: false,
            fatal: false,
            status: 500,
        };
        crate::macros::call_error_hook(
            instance.caption(),
            instance.kind(),
            instance.is_fatal(),
            instance.is_retryable(),
        );
        instance
    }

    /// Create a new Filesystem error
    pub fn filesystem(path: impl Into<String>, source: impl Into<Option<io::Error>>) -> Self {
        // Convert the source parameter
        let source = match source.into() {
            Some(err) => err,
            None => io::Error::other("File operation failed"),
        };

        let instance = Self::Filesystem {
            path: Some(path.into().into()),
            source,
            retryable: false,
            fatal: false,
            status: 500,
        };
        crate::macros::call_error_hook(
            instance.caption(),
            instance.kind(),
            instance.is_fatal(),
            instance.is_retryable(),
        );
        instance
    }

    /// Create a filesystem error with specific source error
    pub fn filesystem_with_source(path: impl Into<PathBuf>, source: io::Error) -> Self {
        let instance = Self::Filesystem {
            path: Some(path.into()),
            source,
            retryable: false,
            fatal: false,
            status: 500,
        };
        crate::macros::call_error_hook(
            instance.caption(),
            instance.kind(),
            instance.is_fatal(),
            instance.is_retryable(),
        );
        instance
    }

    /// Create a new Network error
    pub fn network(
        endpoint: impl Into<String>,
        source: impl Into<Option<Box<dyn StdError + Send + Sync>>>,
    ) -> Self {
        // Convert the source parameter
        let source = source.into();

        let instance = Self::Network {
            endpoint: endpoint.into(),
            source,
            retryable: true,
            fatal: false,
            status: 503,
        };
        crate::macros::call_error_hook(
            instance.caption(),
            instance.kind(),
            instance.is_fatal(),
            instance.is_retryable(),
        );
        instance
    }

    /// Create a network error with specific source error
    pub fn network_with_source(
        endpoint: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync>>,
    ) -> Self {
        let instance = Self::Network {
            endpoint: endpoint.into(),
            source,
            retryable: true,
            fatal: false,
            status: 503,
        };
        crate::macros::call_error_hook(
            instance.caption(),
            instance.kind(),
            instance.is_fatal(),
            instance.is_retryable(),
        );
        instance
    }

    /// Create a new generic error
    pub fn other(message: impl Into<String>) -> Self {
        let instance = Self::Other {
            message: message.into(),
            retryable: false,
            fatal: false,
            status: 500,
        };
        crate::macros::call_error_hook(
            instance.caption(),
            instance.kind(),
            instance.is_fatal(),
            instance.is_retryable(),
        );
        instance
    }

    /// Set whether this error is retryable
    pub fn with_retryable(mut self, retryable: bool) -> Self {
        match &mut self {
            Self::Config { retryable: r, .. } => *r = retryable,
            Self::Filesystem { retryable: r, .. } => *r = retryable,
            Self::Network { retryable: r, .. } => *r = retryable,
            Self::Other { retryable: r, .. } => *r = retryable,
        }
        self
    }

    /// Set whether this error is fatal
    pub fn with_fatal(mut self, fatal: bool) -> Self {
        match &mut self {
            Self::Config { fatal: f, .. } => *f = fatal,
            Self::Filesystem { fatal: f, .. } => *f = fatal,
            Self::Network { fatal: f, .. } => *f = fatal,
            Self::Other { fatal: f, .. } => *f = fatal,
        }
        self
    }

    /// Set the HTTP status code for this error
    pub fn with_status(mut self, status: u16) -> Self {
        match &mut self {
            Self::Config { status: s, .. } => *s = status,
            Self::Filesystem { status: s, .. } => *s = status,
            Self::Network { status: s, .. } => *s = status,
            Self::Other { status: s, .. } => *s = status,
        }
        self
    }

    /// Add a code to this error
    pub fn with_code(self, code: impl Into<String>) -> crate::registry::CodedError<Self> {
        crate::registry::CodedError::new(self, code.into())
    }

    /// Add context to this error
    pub fn context<C: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static>(
        self,
        context: C,
    ) -> crate::context::ContextError<Self, C> {
        crate::context::ContextError::new(self, context)
    }
}