error_forge/
context.rs

1use std::fmt;
2use crate::error::ForgeError;
3
4/// A wrapper error type that attaches contextual information to an error
5#[derive(Debug)]
6pub struct ContextError<E, C> {
7    /// The original error
8    pub error: E,
9    /// The context attached to the error
10    pub context: C,
11}
12
13impl<E, C> ContextError<E, C> {
14    /// Create a new context error wrapping the original error
15    pub fn new(error: E, context: C) -> Self {
16        Self { error, context }
17    }
18    
19    /// Extract the original error, discarding the context
20    pub fn into_error(self) -> E {
21        self.error
22    }
23    
24    /// Map the context to a new type using the provided function
25    pub fn map_context<D, F>(self, f: F) -> ContextError<E, D>
26    where
27        F: FnOnce(C) -> D,
28    {
29        ContextError {
30            error: self.error,
31            context: f(self.context),
32        }
33    }
34    
35    /// Add another layer of context to this error
36    pub fn context<D>(self, context: D) -> ContextError<Self, D>
37    where
38        D: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static,
39    {
40        ContextError::new(self, context)
41    }
42}
43
44impl<E: fmt::Display, C: fmt::Display> fmt::Display for ContextError<E, C> {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(f, "{}: {}", self.context, self.error)
47    }
48}
49
50impl<E: std::error::Error + 'static, C: fmt::Display + fmt::Debug + Send + Sync + 'static> std::error::Error for ContextError<E, C> {
51    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
52        Some(&self.error)
53    }
54}
55
56/// Extension trait for Result types to add context to errors
57pub trait ResultExt<T, E> {
58    /// Adds context to the error variant of the Result
59    fn context<C>(self, context: C) -> Result<T, ContextError<E, C>>;
60    
61    /// Adds context to the error variant using a closure that is only called on error
62    fn with_context<C, F>(self, f: F) -> Result<T, ContextError<E, C>>
63    where
64        F: FnOnce() -> C;
65}
66
67impl<T, E> ResultExt<T, E> for Result<T, E> {
68    fn context<C>(self, context: C) -> Result<T, ContextError<E, C>> {
69        self.map_err(|error| ContextError::new(error, context))
70    }
71    
72    fn with_context<C, F>(self, f: F) -> Result<T, ContextError<E, C>>
73    where
74        F: FnOnce() -> C,
75    {
76        self.map_err(|error| ContextError::new(error, f()))
77    }
78}
79
80// Implement ForgeError for ContextError when the inner error implements ForgeError
81impl<E: ForgeError, C: fmt::Display + fmt::Debug + Send + Sync + 'static> ForgeError for ContextError<E, C> {
82    fn kind(&self) -> &'static str {
83        self.error.kind()
84    }
85    
86    fn caption(&self) -> &'static str {
87        self.error.caption()
88    }
89    
90    fn is_retryable(&self) -> bool {
91        self.error.is_retryable()
92    }
93    
94    fn is_fatal(&self) -> bool {
95        self.error.is_fatal()
96    }
97    
98    fn status_code(&self) -> u16 {
99        self.error.status_code()
100    }
101    
102    fn exit_code(&self) -> i32 {
103        self.error.exit_code()
104    }
105    
106    fn user_message(&self) -> String {
107        format!("{}: {}", self.context, self.error.user_message())
108    }
109    
110    fn dev_message(&self) -> String {
111        format!("{}: {}", self.context, self.error.dev_message())
112    }
113    
114    fn backtrace(&self) -> Option<&std::backtrace::Backtrace> {
115        self.error.backtrace()
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use crate::AppError;
123    
124    #[test]
125    fn test_context_error() {
126        let error = AppError::config("Invalid config");
127        let ctx_error = error.context("Failed to load settings");
128        
129        assert_eq!(ctx_error.to_string(), "Failed to load settings: ⚙️ Configuration Error: Invalid config");
130        assert_eq!(ctx_error.kind(), "Config");
131        assert_eq!(ctx_error.caption(), "⚙️ Configuration");
132    }
133    
134    #[test]
135    fn test_result_context() {
136        let result: Result<(), AppError> = Err(AppError::config("Invalid config"));
137        let ctx_result = result.context("Failed to load settings");
138        
139        assert!(ctx_result.is_err());
140        let err = ctx_result.unwrap_err();
141        assert_eq!(err.to_string(), "Failed to load settings: ⚙️ Configuration Error: Invalid config");
142    }
143}