Skip to main content

error_forge/
async_error.rs

1use std::backtrace::Backtrace;
2use std::error::Error as StdError;
3
4#[cfg(feature = "async")]
5use async_trait::async_trait;
6
7/// Async-aware companion trait to [`ForgeError`](crate::error::ForgeError).
8///
9/// Carries the same sync metadata methods as `ForgeError` plus a single
10/// async hook, [`async_handle`](Self::async_handle), that callers can
11/// override to run an `await` step (logging, telemetry, cleanup) when
12/// an error surfaces in an async context. The default implementation
13/// is a no-op — implementors who do not need an async hook can ignore
14/// the method entirely.
15///
16/// # Example
17///
18/// Requires the `async` cargo feature (which pulls in `async-trait`).
19/// The hidden `#[cfg(feature = "async")]` gate means this doctest is
20/// only compiled when the feature is enabled — under
21/// `cargo test --all-features` it runs; otherwise it is silently
22/// skipped.
23///
24/// ```
25/// # #[cfg(feature = "async")] {
26/// use error_forge::async_error::AsyncForgeError;
27/// use async_trait::async_trait;
28/// use std::error::Error as StdError;
29///
30/// #[derive(Debug)]
31/// struct MyAsyncError { message: String }
32///
33/// impl std::fmt::Display for MyAsyncError {
34///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35///         write!(f, "{}", self.message)
36///     }
37/// }
38///
39/// impl std::error::Error for MyAsyncError {}
40///
41/// #[async_trait]
42/// impl AsyncForgeError for MyAsyncError {
43///     fn kind(&self) -> &'static str { "AsyncExample" }
44///     fn caption(&self) -> &'static str { "Async Example Error" }
45///
46///     // Override the no-op default if you want async behaviour:
47///     async fn async_handle(&self) -> Result<(), Box<dyn StdError + Send + Sync>> {
48///         // Telemetry, cleanup, etc. would go here.
49///         Ok(())
50///     }
51/// }
52/// # }
53/// ```
54///
55/// # Breaking change from `0.9.x`
56///
57/// In `0.9.x`, [`async_handle`](Self::async_handle) was a required
58/// method with no default body, and the [`AppError`](crate::error::AppError)
59/// implementation provided a stub that did nothing. In `1.0`,
60/// [`async_handle`](Self::async_handle) gains a default no-op body
61/// and the stub `AppError` implementation is removed. Implementors
62/// who actually want async behaviour override the default; everyone
63/// else can derive the trait without writing the method.
64///
65/// # Ambiguous method calls
66///
67/// [`AppError`](crate::error::AppError) implements both this trait and
68/// [`ForgeError`](crate::error::ForgeError), and the two share method
69/// names. Cargo unifies features across the dependency graph, so once
70/// any crate enables `async`, a call such as `error.kind()` is
71/// ambiguous (`E0034`) wherever both traits are in scope, for example
72/// after `use error_forge::*`. Import only the trait you call, or use
73/// qualified syntax:
74///
75/// ```
76/// use error_forge::{AppError, ForgeError};
77///
78/// let error = AppError::config("missing key");
79/// assert_eq!(ForgeError::kind(&error), "Config");
80/// ```
81#[cfg(feature = "async")]
82// `async_trait` expands each default `async fn` body into a method that
83// carries a bare `#[must_use]` and returns `Pin<Box<dyn Future>>`. Clippy
84// 1.99 treats that return type as already `#[must_use]` and fires
85// `double_must_use` on the generated code, which callers cannot fix.
86#[allow(clippy::double_must_use)]
87#[async_trait]
88pub trait AsyncForgeError: StdError + Send + Sync + 'static {
89    /// Returns the kind of error, typically matching the enum variant.
90    fn kind(&self) -> &'static str;
91
92    /// Returns a human-readable caption for the error.
93    fn caption(&self) -> &'static str;
94
95    /// Returns true if the operation can be retried.
96    fn is_retryable(&self) -> bool {
97        false
98    }
99
100    /// Returns true if the error is fatal and should terminate the program.
101    fn is_fatal(&self) -> bool {
102        false
103    }
104
105    /// Returns an appropriate HTTP status code for the error.
106    fn status_code(&self) -> u16 {
107        500
108    }
109
110    /// Returns an appropriate process exit code for the error.
111    fn exit_code(&self) -> i32 {
112        1
113    }
114
115    /// Returns a user-facing message that can be shown to end users.
116    fn user_message(&self) -> String {
117        self.to_string()
118    }
119
120    /// Returns a detailed technical message for developers/logs.
121    fn dev_message(&self) -> String {
122        format!("[{}] {}", self.kind(), self)
123    }
124
125    /// Returns a backtrace if available.
126    fn backtrace(&self) -> Option<&Backtrace> {
127        None
128    }
129
130    /// Async hook called when the implementor wants to run an
131    /// `await` step (logging, cleanup, telemetry) on error surfacing.
132    /// The default is a no-op; override if you need behaviour.
133    async fn async_handle(&self) -> Result<(), Box<dyn StdError + Send + Sync>> {
134        Ok(())
135    }
136
137    /// Registers the error with the central error hook (if any).
138    fn register(&self) {
139        crate::macros::call_error_hook(
140            self.caption(),
141            self.kind(),
142            self.is_fatal(),
143            self.is_retryable(),
144        );
145    }
146}
147
148/// Type alias for async error-forge results.
149#[cfg(feature = "async")]
150pub type AsyncResult<T, E> = std::result::Result<T, E>;