Skip to main content

error_forge/
group_macro.rs

1/// Provides macros for grouping errors and generating automatic
2/// conversions.
3// `StdError` is referenced from generated code in the macro body.
4#[allow(unused_imports)]
5use std::error::Error as StdError;
6
7/// Macro for composing multi-error enums with automatic
8/// `From<OtherError>` conversions and full [`ForgeError`] delegation.
9///
10/// Every variant must wrap exactly one source type that itself
11/// implements [`ForgeError`]. The macro generates:
12///
13/// - the enum declaration,
14/// - `Display` and `Error` implementations that forward to the
15///   wrapped source,
16/// - `From<T>` for each wrapped type,
17/// - a [`ForgeError`] impl whose methods delegate directly to the
18///   wrapped source's `ForgeError` methods (no type-erased
19///   downcast, no fallback values).
20///
21/// # Example
22///
23/// ```
24/// use error_forge::{group, AppError};
25///
26/// // `AppError` already implements `ForgeError`, so it can be
27/// // wrapped directly. Other types you wrap with `group!` must
28/// // also implement `ForgeError` (see the next section).
29/// group! {
30///     #[derive(Debug)]
31///     pub enum ServiceError {
32///         App(AppError),
33///     }
34/// }
35///
36/// // `From<AppError>` is generated, so `?` works against any
37/// // function that returns an `AppError`.
38/// let _err: ServiceError = AppError::config("missing").into();
39/// ```
40///
41/// # `ForgeError` requirement
42///
43/// Each wrapped source type must implement [`ForgeError`].
44/// `#[derive(ModError)]` (the `derive` feature) implements it for
45/// you. [`define_errors!`] does **not**: it generates inherent
46/// methods with the same names (`kind`, `caption`, `is_retryable`,
47/// `is_fatal`, `status_code`, `exit_code`) but no trait impl, so a
48/// `define_errors!` enum needs a short delegating impl before it can
49/// be grouped. The same applies to a foreign type such as
50/// `std::io::Error`: wrap it in a variant of an enum that implements
51/// [`ForgeError`] and group that enum.
52///
53/// ```
54/// use error_forge::{define_errors, group, AppError, ForgeError};
55///
56/// define_errors! {
57///     pub enum FsError {
58///         #[error(display = "Could not write {path}", path)]
59///         #[kind(Filesystem, status = 500)]
60///         WriteFailed { path: String },
61///     }
62/// }
63///
64/// // `FsError::kind(self)` resolves to the inherent method the
65/// // macro generated, not back to this trait method.
66/// impl ForgeError for FsError {
67///     fn kind(&self) -> &'static str { FsError::kind(self) }
68///     fn caption(&self) -> &'static str { FsError::caption(self) }
69///     fn is_retryable(&self) -> bool { FsError::is_retryable(self) }
70///     fn is_fatal(&self) -> bool { FsError::is_fatal(self) }
71///     fn status_code(&self) -> u16 { FsError::status_code(self) }
72///     fn exit_code(&self) -> i32 { FsError::exit_code(self) }
73/// }
74///
75/// group! {
76///     #[derive(Debug)]
77///     pub enum ServiceError {
78///         App(AppError),
79///         Fs(FsError),
80///     }
81/// }
82///
83/// let err: ServiceError = FsError::writefailed("out.log".to_string()).into();
84/// assert_eq!(err.to_string(), "Could not write out.log");
85/// assert_eq!(err.kind(), "Filesystem");
86/// assert_eq!(err.status_code(), 500);
87/// ```
88///
89/// This is a **breaking change from `0.9.x`**, where `group!`
90/// accepted any wrapped type but the resulting `ForgeError` impl
91/// was silently incorrect — every method returned default
92/// fallback values regardless of the wrapped type. The `1.0`
93/// rewrite removes the type-erased downcast and trades it for a
94/// trait bound the compiler can verify.
95///
96/// [`ForgeError`]: crate::error::ForgeError
97/// [`define_errors!`]: crate::define_errors
98#[macro_export]
99macro_rules! group {
100    (
101        $(#[$meta:meta])*
102        $vis:vis enum $name:ident {
103            $(
104                $(#[$vmeta:meta])*
105                $variant:ident($source_type:ty)
106            ),* $(,)?
107        }
108    ) => {
109        $(#[$meta])*
110        $vis enum $name {
111            $(
112                $(#[$vmeta])*
113                $variant($source_type),
114            )*
115        }
116
117        impl ::std::fmt::Display for $name {
118            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
119                match self {
120                    $(
121                        Self::$variant(source) => ::std::fmt::Display::fmt(source, f),
122                    )*
123                }
124            }
125        }
126
127        impl ::std::error::Error for $name {
128            fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> {
129                match self {
130                    $(
131                        Self::$variant(source) => {
132                            ::std::option::Option::Some(source as &(dyn ::std::error::Error + 'static))
133                        }
134                    )*
135                }
136            }
137        }
138
139        $(
140            impl ::std::convert::From<$source_type> for $name {
141                fn from(source: $source_type) -> Self {
142                    Self::$variant(source)
143                }
144            }
145        )*
146
147        impl $crate::error::ForgeError for $name {
148            fn kind(&self) -> &'static str {
149                match self {
150                    $(
151                        Self::$variant(source) => $crate::error::ForgeError::kind(source),
152                    )*
153                }
154            }
155
156            fn caption(&self) -> &'static str {
157                match self {
158                    $(
159                        Self::$variant(source) => $crate::error::ForgeError::caption(source),
160                    )*
161                }
162            }
163
164            fn is_retryable(&self) -> bool {
165                match self {
166                    $(
167                        Self::$variant(source) => $crate::error::ForgeError::is_retryable(source),
168                    )*
169                }
170            }
171
172            fn is_fatal(&self) -> bool {
173                match self {
174                    $(
175                        Self::$variant(source) => $crate::error::ForgeError::is_fatal(source),
176                    )*
177                }
178            }
179
180            fn status_code(&self) -> u16 {
181                match self {
182                    $(
183                        Self::$variant(source) => $crate::error::ForgeError::status_code(source),
184                    )*
185                }
186            }
187
188            fn exit_code(&self) -> i32 {
189                match self {
190                    $(
191                        Self::$variant(source) => $crate::error::ForgeError::exit_code(source),
192                    )*
193                }
194            }
195
196            fn user_message(&self) -> ::std::string::String {
197                match self {
198                    $(
199                        Self::$variant(source) => $crate::error::ForgeError::user_message(source),
200                    )*
201                }
202            }
203
204            fn dev_message(&self) -> ::std::string::String {
205                match self {
206                    $(
207                        Self::$variant(source) => $crate::error::ForgeError::dev_message(source),
208                    )*
209                }
210            }
211        }
212    };
213}