1use crate::error::ForgeError;
2use std::collections::HashMap;
3use std::fmt;
4use std::sync::OnceLock;
5use std::sync::RwLock;
6
7pub struct ErrorRegistry {
9 codes: RwLock<HashMap<String, ErrorCodeInfo>>,
11}
12
13#[derive(Clone, Debug)]
18#[non_exhaustive]
19pub struct ErrorCodeInfo {
20 pub code: String,
22 pub description: String,
24 pub documentation_url: Option<String>,
26 pub retryable: bool,
28}
29
30impl ErrorRegistry {
31 fn new() -> Self {
33 Self {
34 codes: RwLock::new(HashMap::new()),
35 }
36 }
37
38 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 pub fn get_code_info(&self, code: &str) -> Option<ErrorCodeInfo> {
70 self.with_code_info(code, ErrorCodeInfo::clone)
71 }
72
73 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 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 pub fn global() -> &'static ErrorRegistry {
92 static REGISTRY: OnceLock<ErrorRegistry> = OnceLock::new();
93 REGISTRY.get_or_init(ErrorRegistry::new)
94 }
95}
96
97#[derive(Debug)]
105#[non_exhaustive]
106pub struct CodedError<E> {
107 pub error: E,
109 pub code: String,
111 pub retryable: Option<bool>,
113 pub fatal: bool,
115 pub status: Option<u16>,
117}
118
119impl<E> CodedError<E> {
120 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 pub fn code_info(&self) -> Option<ErrorCodeInfo> {
150 ErrorRegistry::global().get_code_info(&self.code)
151 }
152
153 pub fn with_retryable(mut self, retryable: bool) -> Self {
155 self.retryable = Some(retryable);
156 self
157 }
158
159 pub fn with_fatal(mut self, fatal: bool) -> Self {
161 self.fatal = fatal;
162 self
163 }
164
165 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
184impl<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 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
237pub trait WithErrorCode<E> {
239 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
249pub 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}