Skip to main content

openlark_core/error/
prelude.rs

1//! 现代化错误处理系统预置模块
2//!
3//! 提供新thiserror架构的完整错误处理组件导入
4
5// 核心类型重新导出(主要推荐 CoreError)
6pub use super::codes::ErrorCode;
7pub use super::context::ErrorContext;
8pub use super::core::{BuilderKind, ErrorBuilder, ErrorRecord};
9pub use super::core::{RecoveryStrategy, RetryPolicy};
10pub use super::traits::{ErrorSeverity, ErrorType};
11pub use super::{CoreError, ErrorId, SDKResult};
12
13// 特征系统重新导出
14pub use super::traits::{ErrorContextTrait, ErrorFormatTrait, ErrorTrait, FullErrorTrait};
15
16pub use super::core::{
17    api_error, authentication_error, business_error, configuration_error, network_error,
18    network_error_with_details, rate_limit_error, serialization_error, service_unavailable_error,
19    timeout_error, validation_error,
20};
21
22// 常用的导入组合
23/// 常用导入组合模块
24///
25/// 包含错误处理核心类型、集合类型和时间类型,方便快速导入
26pub mod common_imports {
27    pub use super::*;
28    pub use std::collections::HashMap;
29    pub use std::time::Duration;
30}
31
32/// 创建网络错误的宏
33#[macro_export]
34macro_rules! network_err {
35    ($msg:expr) => {
36        $crate::error::network_error($msg)
37    };
38    ($fmt:expr, $($arg:tt)*) => {
39        $crate::error::network_error(format!($fmt, $($arg)*))
40    };
41}
42
43/// 创建认证错误的宏
44#[macro_export]
45macro_rules! auth_err {
46    ($msg:expr) => {
47        $crate::error::authentication_error($msg)
48    };
49    ($fmt:expr, $($arg:tt)*) => {
50        $crate::error::authentication_error(format!($fmt, $($arg)*))
51    };
52}
53
54/// 创建验证错误的宏
55#[macro_export]
56macro_rules! validation_err {
57    ($field:expr, $msg:expr) => {
58        $crate::error::validation_error($field, $msg)
59    };
60    ($field:expr, $fmt:expr, $($arg:tt)*) => {
61        $crate::error::validation_error($field, format!($fmt, $($arg)*))
62    };
63}
64
65/// 创建业务错误的宏
66#[macro_export]
67macro_rules! business_err {
68    ($msg:expr) => {
69        $crate::error::business_error($msg)
70    };
71    ($fmt:expr, $($arg:tt)*) => {
72        $crate::error::business_error(format!($fmt, $($arg)*))
73    };
74}
75
76/// 创建API错误的宏
77#[macro_export]
78macro_rules! api_err {
79    ($status:expr, $endpoint:expr, $msg:expr) => {
80        $crate::error::api_error($status, $endpoint, $msg, None::<String>)
81    };
82    ($status:expr, $endpoint:expr, $fmt:expr, $($arg:tt)*) => {
83        $crate::error::api_error($status, $endpoint, format!($fmt, $($arg)*), None::<String>)
84    };
85}
86
87/// 条件错误返回宏(现代化版本)
88#[macro_export]
89macro_rules! ensure {
90    ($condition:expr, $error:expr) => {
91        if !$condition {
92            return Err(Into::<$crate::error::CoreError>::into($error));
93        }
94    };
95    ($condition:expr, $fmt:expr, $($arg:tt)*) => {
96        if !$condition {
97            return Err(Into::<$crate::error::CoreError>::into(
98                $crate::error::validation_error("condition", format!($fmt, $($arg)*))
99            ));
100        }
101    };
102}
103
104/// 快速验证宏
105#[macro_export]
106macro_rules! validate {
107    ($field:expr, $value:expr, $error_msg:expr) => {
108        if !$value {
109            return Err(Into::<$crate::error::CoreError>::into(
110                $crate::error::validation_error($field, $error_msg)
111            ));
112        }
113    };
114    ($field:expr, $value:expr, $error_msg:expr, $($arg:tt)*) => {
115        if !$value {
116            return Err(Into::<$crate::error::CoreError>::into(
117                $crate::error::validation_error($field, format!($error_msg, $($arg)*))
118            ));
119        }
120    };
121}
122
123/// 错误匹配和处理宏
124#[macro_export]
125macro_rules! handle_error {
126    ($result:expr, {
127        $pattern:pat => $handler:expr,
128        * => $default_handler:expr,
129    }) => {
130        match $result {
131            Ok(value) => value,
132            Err($pattern) => $handler,
133            Err(error) => $default_handler(error),
134        }
135    };
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn test_modern_prelude_imports() {
144        // 确保所有重新导出的类型都可以使用
145        let _error: CoreError = network_error("测试");
146        let _result: SDKResult<()> = Ok(());
147        let _severity: ErrorSeverity = ErrorSeverity::Warning;
148        let _code: ErrorCode = ErrorCode::BadRequest;
149        let _lark_error: CoreError = network_error("测试");
150    }
151
152    #[test]
153    fn test_modern_convenience_macros() {
154        let error = network_err!("连接失败");
155        assert!(error.is_network_error());
156
157        let error = auth_err!("认证失败");
158        assert!(error.is_auth_error());
159
160        let error = validation_err!("email", "格式不正确");
161        assert!(error.is_validation_error());
162
163        let error = api_err!(404, "/api/users", "用户不存在");
164        assert!(error.is_api_error());
165    }
166
167    #[test]
168    fn test_builder_macro() {
169        let error = validation_error("email", "邮箱格式不正确");
170
171        assert!(error.is_validation_error());
172        assert_eq!(error.context().get_context("field"), Some("email"));
173    }
174
175    #[test]
176    fn test_ensure_macro() {
177        let result = || -> SDKResult<()> {
178            ensure!(true, validation_error("test", "不应该失败"));
179            ensure!(false, validation_error("test", "应该失败"));
180            Ok(())
181        }();
182
183        assert!(result.is_err());
184        assert!(result.unwrap_err().is_validation_error());
185    }
186
187    #[test]
188    fn test_validate_macro() {
189        let result = || -> SDKResult<()> {
190            validate!("email", "test@example".contains("@"), "邮箱格式不正确");
191            Ok(())
192        }();
193
194        assert!(result.is_ok());
195
196        let result = || -> SDKResult<()> {
197            validate!("email", "invalid_email".contains("@"), "邮箱格式不正确");
198            Ok(())
199        }();
200
201        assert!(result.is_err());
202        assert!(result.unwrap_err().is_validation_error());
203    }
204
205    #[test]
206    fn test_modern_error_creation() {
207        let error = api_error(
208            404,
209            "/api/v1/users/123",
210            "用户不存在",
211            Some("req-123".to_string()),
212        );
213
214        assert!(error.is_api_error());
215        assert_eq!(error.severity(), ErrorSeverity::Warning);
216        assert!(!error.is_retryable());
217        assert!(!error.is_user_error());
218        assert_eq!(error.context().request_id(), Some("req-123"));
219    }
220}