error_forge/async_error.rs
1use std::error::Error as StdError;
2use std::backtrace::Backtrace;
3
4#[cfg(feature = "async")]
5use async_trait::async_trait;
6
7/// An async-compatible version of the ForgeError trait.
8///
9/// This trait extends the standard error capabilities with async support,
10/// allowing for async error handling in futures and async functions.
11///
12/// # Example
13///
14/// ```rust,ignore
15/// use error_forge::async_error::AsyncForgeError;
16/// use async_trait::async_trait;
17///
18/// #[derive(Debug)]
19/// struct MyAsyncError { message: String }
20///
21/// impl std::fmt::Display for MyAsyncError {
22/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23/// write!(f, "{}", self.message)
24/// }
25/// }
26///
27/// impl std::error::Error for MyAsyncError {}
28///
29/// #[async_trait]
30/// impl AsyncForgeError for MyAsyncError {
31/// fn kind(&self) -> &'static str {
32/// "AsyncExample"
33/// }
34///
35/// fn caption(&self) -> &'static str {
36/// "Async Example Error"
37/// }
38///
39/// async fn async_handle(&self) -> Result<(), Box<dyn StdError + Send + Sync>> {
40/// // Perform async error handling here
41/// println!("Handling async error: {}", self);
42/// Ok(())
43/// }
44/// }
45/// ```
46#[cfg(feature = "async")]
47#[async_trait]
48pub trait AsyncForgeError: StdError + Send + Sync + 'static {
49 /// Returns the kind of error, typically matching the enum variant
50 fn kind(&self) -> &'static str;
51
52 /// Returns a human-readable caption for the error
53 fn caption(&self) -> &'static str;
54
55 /// Returns true if the operation can be retried
56 fn is_retryable(&self) -> bool {
57 false
58 }
59
60 /// Returns true if the error is fatal and should terminate the program
61 fn is_fatal(&self) -> bool {
62 false
63 }
64
65 /// Returns an appropriate HTTP status code for the error
66 fn status_code(&self) -> u16 {
67 500
68 }
69
70 /// Returns an appropriate process exit code for the error
71 fn exit_code(&self) -> i32 {
72 1
73 }
74
75 /// Returns a user-facing message that can be shown to end users
76 fn user_message(&self) -> String {
77 self.to_string()
78 }
79
80 /// Returns a detailed technical message for developers/logs
81 fn dev_message(&self) -> String {
82 format!("[{}] {}", self.kind(), self)
83 }
84
85 /// Returns a backtrace if available
86 fn backtrace(&self) -> Option<&Backtrace> {
87 None
88 }
89
90 /// Async method to handle the error. This allows implementing custom
91 /// async error handling logic.
92 async fn async_handle(&self) -> Result<(), Box<dyn StdError + Send + Sync>>;
93
94 /// Registers the error with the central error registry
95 fn register(&self) {
96 crate::macros::call_error_hook(self.caption(), self.kind(), self.is_fatal(), self.is_retryable());
97 }
98}
99
100/// Type alias for async error-forge results.
101#[cfg(feature = "async")]
102pub type AsyncResult<T, E> = std::result::Result<T, E>;