Skip to main content

error_forge/
context.rs

1use crate::error::ForgeError;
2use std::fmt;
3
4/// A wrapper error type that attaches contextual information to
5/// an error.
6///
7/// Marked `#[non_exhaustive]` so future minor releases can add new
8/// fields without breaking callers. External code must not
9/// construct `ContextError` via struct-literal syntax; use
10/// [`ContextError::new`] or [`ResultExt::context`] /
11/// [`ResultExt::with_context`].
12#[derive(Debug)]
13#[non_exhaustive]
14pub struct ContextError<E, C> {
15    /// The original error
16    pub error: E,
17    /// The context attached to the error
18    pub context: C,
19}
20
21impl<E, C> ContextError<E, C> {
22    /// Create a new context error wrapping the original error
23    pub fn new(error: E, context: C) -> Self {
24        Self { error, context }
25    }
26
27    /// Extract the original error, discarding the context
28    pub fn into_error(self) -> E {
29        self.error
30    }
31
32    /// Map the context to a new type using the provided function
33    pub fn map_context<D, F>(self, f: F) -> ContextError<E, D>
34    where
35        F: FnOnce(C) -> D,
36    {
37        ContextError {
38            error: self.error,
39            context: f(self.context),
40        }
41    }
42
43    /// Add another layer of context to this error
44    pub fn context<D>(self, context: D) -> ContextError<Self, D>
45    where
46        D: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static,
47    {
48        ContextError::new(self, context)
49    }
50}
51
52impl<E: fmt::Display, C: fmt::Display> fmt::Display for ContextError<E, C> {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        write!(f, "{}: {}", self.context, self.error)
55    }
56}
57
58impl<E: std::error::Error + 'static, C: fmt::Display + fmt::Debug + Send + Sync + 'static>
59    std::error::Error for ContextError<E, C>
60{
61    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
62        Some(&self.error)
63    }
64}
65
66/// Extension trait for Result types to add context to errors
67///
68/// `anyhow::Context` also adds a `context` method to `Result`. With both
69/// traits in scope, `result.context(...)` is ambiguous; import only one
70/// of them in a module, or call this one by path.
71///
72/// # Example
73///
74/// ```
75/// use error_forge::{AppError, ResultExt};
76///
77/// let result: Result<(), AppError> = Err(AppError::config("bad value"));
78/// let wrapped = ResultExt::context(result, "loading settings");
79/// assert!(wrapped.unwrap_err().to_string().starts_with("loading settings: "));
80/// ```
81pub trait ResultExt<T, E> {
82    /// Adds context to the error variant of the Result
83    fn context<C>(self, context: C) -> Result<T, ContextError<E, C>>;
84
85    /// Adds context to the error variant using a closure that is only called on error
86    fn with_context<C, F>(self, f: F) -> Result<T, ContextError<E, C>>
87    where
88        F: FnOnce() -> C;
89}
90
91impl<T, E> ResultExt<T, E> for Result<T, E> {
92    fn context<C>(self, context: C) -> Result<T, ContextError<E, C>> {
93        self.map_err(|error| ContextError::new(error, context))
94    }
95
96    fn with_context<C, F>(self, f: F) -> Result<T, ContextError<E, C>>
97    where
98        F: FnOnce() -> C,
99    {
100        self.map_err(|error| ContextError::new(error, f()))
101    }
102}
103
104// Implement ForgeError for ContextError when the inner error implements ForgeError
105impl<E: ForgeError, C: fmt::Display + fmt::Debug + Send + Sync + 'static> ForgeError
106    for ContextError<E, C>
107{
108    fn kind(&self) -> &'static str {
109        self.error.kind()
110    }
111
112    fn caption(&self) -> &'static str {
113        self.error.caption()
114    }
115
116    fn is_retryable(&self) -> bool {
117        self.error.is_retryable()
118    }
119
120    fn is_fatal(&self) -> bool {
121        self.error.is_fatal()
122    }
123
124    fn status_code(&self) -> u16 {
125        self.error.status_code()
126    }
127
128    fn exit_code(&self) -> i32 {
129        self.error.exit_code()
130    }
131
132    fn user_message(&self) -> String {
133        format!("{}: {}", self.context, self.error.user_message())
134    }
135
136    fn dev_message(&self) -> String {
137        format!("{}: {}", self.context, self.error.dev_message())
138    }
139
140    fn backtrace(&self) -> Option<&std::backtrace::Backtrace> {
141        self.error.backtrace()
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148    use crate::AppError;
149
150    #[test]
151    fn test_context_error() {
152        let error = AppError::config("Invalid config");
153        let ctx_error = error.context("Failed to load settings");
154
155        assert_eq!(
156            ctx_error.to_string(),
157            "Failed to load settings: ⚙️ Configuration Error: Invalid config"
158        );
159        assert_eq!(ctx_error.kind(), "Config");
160        assert_eq!(ctx_error.caption(), "⚙️ Configuration");
161    }
162
163    #[test]
164    fn test_result_context() {
165        let result: Result<(), AppError> = Err(AppError::config("Invalid config"));
166        let ctx_result = result.context("Failed to load settings");
167
168        assert!(ctx_result.is_err());
169        let err = ctx_result.unwrap_err();
170        assert_eq!(
171            err.to_string(),
172            "Failed to load settings: ⚙️ Configuration Error: Invalid config"
173        );
174    }
175}