Skip to main content

error_forge/
registry.rs

1use crate::error::ForgeError;
2use std::collections::HashMap;
3use std::fmt;
4use std::sync::OnceLock;
5use std::sync::RwLock;
6
7/// A central registry for error codes and metadata
8pub struct ErrorRegistry {
9    /// Maps error codes to their descriptions
10    codes: RwLock<HashMap<String, ErrorCodeInfo>>,
11}
12
13/// Metadata for a registered error code.
14///
15/// Marked `#[non_exhaustive]` so future minor releases can add new
16/// fields (e.g. severity, tags, owner) without breaking callers.
17#[derive(Clone, Debug)]
18#[non_exhaustive]
19pub struct ErrorCodeInfo {
20    /// The error code (e.g. "AUTH-001")
21    pub code: String,
22    /// A human-readable description of this error type
23    pub description: String,
24    /// A URL to documentation about this error, if available
25    pub documentation_url: Option<String>,
26    /// Whether this error is expected to be retryable
27    pub retryable: bool,
28}
29
30impl ErrorRegistry {
31    /// Create a new empty error registry
32    fn new() -> Self {
33        Self {
34            codes: RwLock::new(HashMap::new()),
35        }
36    }
37
38    /// Register an error code with metadata
39    pub fn register_code(
40        &self,
41        code: String,
42        description: String,
43        documentation_url: Option<String>,
44        retryable: bool,
45    ) -> Result<(), String> {
46        let mut codes = match self.codes.write() {
47            Ok(codes) => codes,
48            Err(_) => return Err("Failed to acquire write lock on error registry".to_string()),
49        };
50
51        if codes.contains_key(&code) {
52            return Err(format!("Error code '{code}' is already registered"));
53        }
54
55        codes.insert(
56            code.clone(),
57            ErrorCodeInfo {
58                code,
59                description,
60                documentation_url,
61                retryable,
62            },
63        );
64
65        Ok(())
66    }
67
68    /// Get info about a registered error code
69    pub fn get_code_info(&self, code: &str) -> Option<ErrorCodeInfo> {
70        self.with_code_info(code, ErrorCodeInfo::clone)
71    }
72
73    /// Run `f` on the entry for `code` under the read lock, without
74    /// cloning it. `f` must not call back into the registry.
75    fn with_code_info<R>(&self, code: &str, f: impl FnOnce(&ErrorCodeInfo) -> R) -> Option<R> {
76        match self.codes.read() {
77            Ok(codes) => codes.get(code).map(f),
78            Err(_) => None,
79        }
80    }
81
82    /// Check if an error code is registered
83    pub fn is_registered(&self, code: &str) -> bool {
84        match self.codes.read() {
85            Ok(codes) => codes.contains_key(code),
86            Err(_) => false,
87        }
88    }
89
90    /// Get the global error registry instance
91    pub fn global() -> &'static ErrorRegistry {
92        static REGISTRY: OnceLock<ErrorRegistry> = OnceLock::new();
93        REGISTRY.get_or_init(ErrorRegistry::new)
94    }
95}
96
97/// An error with an associated error code.
98///
99/// Marked `#[non_exhaustive]` so future minor releases can add new
100/// fields without breaking callers. External code must not
101/// construct `CodedError` via struct-literal syntax; use
102/// [`CodedError::new`] or the [`WithErrorCode::with_code`]
103/// extension method.
104#[derive(Debug)]
105#[non_exhaustive]
106pub struct CodedError<E> {
107    /// The original error
108    pub error: E,
109    /// The error code
110    pub code: String,
111    /// Per-instance override for retryability
112    pub retryable: Option<bool>,
113    /// Whether this error is fatal
114    pub fatal: bool,
115    /// Per-instance override for status code
116    pub status: Option<u16>,
117}
118
119impl<E> CodedError<E> {
120    /// Wrap an error with a stable code.
121    ///
122    /// The code is **not** auto-registered in the global registry.
123    /// Pre-register the code at startup with
124    /// [`register_error_code`] if you want documentation URLs,
125    /// per-code descriptions, or retryability metadata to flow
126    /// through [`CodedError::code_info`] / [`CodedError::is_retryable`].
127    ///
128    /// # Behaviour change since `1.0.0`
129    ///
130    /// Prior `0.9.x` releases auto-registered the code from inside
131    /// `CodedError::new`, which took a write lock on the global
132    /// registry on the first occurrence of every new code per
133    /// process. That lazy-registration step is gone in `1.0` — the
134    /// hot path is now a single allocation (the `String` from
135    /// `code.into()`) and zero locking. Code metadata that was
136    /// pre-registered via [`register_error_code`] continues to be
137    /// consulted via [`CodedError::code_info`] / `is_retryable`.
138    pub fn new(error: E, code: impl Into<String>) -> Self {
139        Self {
140            error,
141            code: code.into(),
142            retryable: None,
143            fatal: false,
144            status: None,
145        }
146    }
147
148    /// Get information about this error code from the registry
149    pub fn code_info(&self) -> Option<ErrorCodeInfo> {
150        ErrorRegistry::global().get_code_info(&self.code)
151    }
152
153    /// Set whether this error is retryable
154    pub fn with_retryable(mut self, retryable: bool) -> Self {
155        self.retryable = Some(retryable);
156        self
157    }
158
159    /// Set whether this error is fatal
160    pub fn with_fatal(mut self, fatal: bool) -> Self {
161        self.fatal = fatal;
162        self
163    }
164
165    /// Set the HTTP status code for this error
166    pub fn with_status(mut self, status: u16) -> Self {
167        self.status = Some(status);
168        self
169    }
170}
171
172impl<E: fmt::Display> fmt::Display for CodedError<E> {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        write!(f, "[{}] {}", self.code, self.error)
175    }
176}
177
178impl<E: std::error::Error + 'static> std::error::Error for CodedError<E> {
179    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
180        Some(&self.error)
181    }
182}
183
184// Implement ForgeError for CodedError when the inner error implements ForgeError
185impl<E: ForgeError> ForgeError for CodedError<E> {
186    fn kind(&self) -> &'static str {
187        self.error.kind()
188    }
189
190    fn caption(&self) -> &'static str {
191        self.error.caption()
192    }
193
194    fn is_retryable(&self) -> bool {
195        self.retryable.unwrap_or_else(|| {
196            ErrorRegistry::global()
197                .with_code_info(&self.code, |info| info.retryable)
198                .unwrap_or_else(|| self.error.is_retryable())
199        })
200    }
201
202    fn is_fatal(&self) -> bool {
203        self.fatal || self.error.is_fatal()
204    }
205
206    fn status_code(&self) -> u16 {
207        self.status.unwrap_or_else(|| self.error.status_code())
208    }
209
210    fn exit_code(&self) -> i32 {
211        self.error.exit_code()
212    }
213
214    fn user_message(&self) -> String {
215        format!("[{}] {}", self.code, self.error.user_message())
216    }
217
218    fn dev_message(&self) -> String {
219        // The inner message is built before taking the registry lock so
220        // user code never runs while the lock is held.
221        let inner = self.error.dev_message();
222        ErrorRegistry::global()
223            .with_code_info(&self.code, |info| {
224                info.documentation_url
225                    .as_ref()
226                    .map(|url| format!("[{}] {} ({})", self.code, inner, url))
227            })
228            .flatten()
229            .unwrap_or_else(|| format!("[{}] {}", self.code, inner))
230    }
231
232    fn backtrace(&self) -> Option<&std::backtrace::Backtrace> {
233        self.error.backtrace()
234    }
235}
236
237/// Extension trait for adding error codes
238pub trait WithErrorCode<E> {
239    /// Attach an error code to an error
240    fn with_code(self, code: impl Into<String>) -> CodedError<E>;
241}
242
243impl<E> WithErrorCode<E> for E {
244    fn with_code(self, code: impl Into<String>) -> CodedError<E> {
245        CodedError::new(self, code)
246    }
247}
248
249/// Register an error code in the global registry
250pub fn register_error_code(
251    code: impl Into<String>,
252    description: impl Into<String>,
253    documentation_url: Option<impl Into<String>>,
254    retryable: bool,
255) -> Result<(), String> {
256    ErrorRegistry::global().register_code(
257        code.into(),
258        description.into(),
259        documentation_url.map(|url| url.into()),
260        retryable,
261    )
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::AppError;
268
269    #[test]
270    fn test_error_with_code() {
271        let error = AppError::config("Invalid config").with_code("CONFIG-001");
272
273        assert_eq!(
274            error.to_string(),
275            "[CONFIG-001] ⚙️ Configuration Error: Invalid config"
276        );
277    }
278
279    #[test]
280    fn test_register_error_code() {
281        let _ = register_error_code(
282            "AUTH-001",
283            "Authentication failed due to invalid credentials",
284            Some("https://docs.example.com/errors/auth-001"),
285            true,
286        );
287
288        let info = ErrorRegistry::global().get_code_info("AUTH-001");
289        assert!(info.is_some());
290        let info = info.unwrap();
291        assert_eq!(info.code, "AUTH-001");
292        assert_eq!(
293            info.description,
294            "Authentication failed due to invalid credentials"
295        );
296        assert_eq!(
297            info.documentation_url,
298            Some("https://docs.example.com/errors/auth-001".to_string())
299        );
300        assert!(info.retryable);
301    }
302}