Skip to main content

wae_types/
error.rs

1//! 错误类型定义
2
3use serde::{Deserialize, Serialize};
4use std::fmt;
5
6/// 错误类型标识
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8pub enum ErrorKind {
9    /// 验证错误
10    Validation,
11    /// 网络错误
12    Network,
13    /// 存储错误
14    Storage,
15    /// 内部错误
16    Internal,
17    /// 未找到
18    NotFound,
19    /// 权限错误
20    Permission,
21    /// 超时错误
22    Timeout,
23    /// 配置错误
24    Config,
25}
26
27/// 验证错误类型
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub enum ValidationErrorKind {
30    /// 无效格式
31    InvalidFormat {
32        /// 字段名
33        field: String,
34        /// 期望值
35        expected: String,
36    },
37    /// 值超出范围
38    OutOfRange {
39        /// 字段名
40        field: String,
41        /// 最小值
42        min: Option<String>,
43        /// 最大值
44        max: Option<String>,
45    },
46    /// 必填字段缺失
47    Required {
48        /// 字段名
49        field: String,
50    },
51    /// 值已存在
52    AlreadyExists {
53        /// 字段名
54        field: String,
55        /// 值
56        value: String,
57    },
58    /// 值不允许
59    NotAllowed {
60        /// 字段名
61        field: String,
62        /// 允许的值
63        allowed: Vec<String>,
64    },
65    /// 自定义验证错误
66    CustomValidation {
67        /// 字段名
68        field: String,
69        /// 错误消息
70        message: String,
71    },
72}
73
74impl fmt::Display for ValidationErrorKind {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        match self {
77            ValidationErrorKind::InvalidFormat { field, expected } => {
78                write!(f, "invalid_format: field '{}' expected {}", field, expected)
79            }
80            ValidationErrorKind::OutOfRange { field, min, max } => {
81                write!(f, "out_of_range: field '{}'", field)?;
82                if let Some(min) = min {
83                    write!(f, " min={}", min)?;
84                }
85                if let Some(max) = max {
86                    write!(f, " max={}", max)?;
87                }
88                Ok(())
89            }
90            ValidationErrorKind::Required { field } => write!(f, "required: field '{}' is required", field),
91            ValidationErrorKind::AlreadyExists { field, value } => {
92                write!(f, "already_exists: field '{}' with value '{}' already exists", field, value)
93            }
94            ValidationErrorKind::NotAllowed { field, allowed } => {
95                write!(f, "not_allowed: field '{}' must be one of {:?}", field, allowed)
96            }
97            ValidationErrorKind::CustomValidation { field, message } => {
98                write!(f, "validation_error: field '{}' - {}", field, message)
99            }
100        }
101    }
102}
103
104/// 网络错误类型
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
106pub enum NetworkErrorKind {
107    /// 连接失败
108    ConnectionFailed,
109    /// DNS 解析失败
110    DnsFailed,
111    /// DNS 解析失败
112    DnsResolutionFailed,
113    /// 请求超时
114    Timeout,
115    /// SSL/TLS 错误
116    TlsError,
117    /// 协议错误
118    ProtocolError,
119}
120
121impl fmt::Display for NetworkErrorKind {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        match self {
124            NetworkErrorKind::ConnectionFailed => write!(f, "connection_failed"),
125            NetworkErrorKind::DnsFailed => write!(f, "dns_failed"),
126            NetworkErrorKind::DnsResolutionFailed => write!(f, "dns_resolution_failed"),
127            NetworkErrorKind::Timeout => write!(f, "timeout"),
128            NetworkErrorKind::TlsError => write!(f, "tls_error"),
129            NetworkErrorKind::ProtocolError => write!(f, "protocol_error"),
130        }
131    }
132}
133
134/// 存储错误类型
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
136pub enum StorageErrorKind {
137    /// 读取失败
138    ReadFailed,
139    /// 写入失败
140    WriteFailed,
141    /// 删除失败
142    DeleteFailed,
143    /// 容量不足
144    InsufficientCapacity,
145    /// 数据损坏
146    DataCorruption,
147    /// 文件未找到
148    FileNotFound,
149}
150
151impl fmt::Display for StorageErrorKind {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        match self {
154            StorageErrorKind::ReadFailed => write!(f, "read_failed"),
155            StorageErrorKind::WriteFailed => write!(f, "write_failed"),
156            StorageErrorKind::DeleteFailed => write!(f, "delete_failed"),
157            StorageErrorKind::InsufficientCapacity => write!(f, "insufficient_capacity"),
158            StorageErrorKind::DataCorruption => write!(f, "data_corruption"),
159            StorageErrorKind::FileNotFound => write!(f, "file_not_found"),
160        }
161    }
162}
163
164/// 数据库错误类型
165#[derive(Debug, Clone, Serialize, Deserialize)]
166pub enum DatabaseErrorKind {
167    /// 连接失败
168    ConnectionFailed {
169        /// 错误消息
170        message: String,
171    },
172    /// 查询失败
173    QueryFailed {
174        /// 查询语句
175        query: Option<String>,
176        /// 错误消息
177        message: String,
178    },
179    /// 执行失败
180    ExecuteFailed {
181        /// 执行语句
182        query: Option<String>,
183        /// 错误消息
184        message: String,
185    },
186    /// 事务失败
187    TransactionFailed {
188        /// 错误消息
189        message: String,
190    },
191    /// 迁移失败
192    MigrationFailed {
193        /// 错误消息
194        message: String,
195    },
196}
197
198impl fmt::Display for DatabaseErrorKind {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        match self {
201            DatabaseErrorKind::ConnectionFailed { message } => {
202                write!(f, "connection_failed: {}", message)
203            }
204            DatabaseErrorKind::QueryFailed { query, message } => {
205                if let Some(q) = query {
206                    write!(f, "query_failed ({}): {}", q, message)
207                }
208                else {
209                    write!(f, "query_failed: {}", message)
210                }
211            }
212            DatabaseErrorKind::ExecuteFailed { query, message } => {
213                if let Some(q) = query {
214                    write!(f, "execute_failed ({}): {}", q, message)
215                }
216                else {
217                    write!(f, "execute_failed: {}", message)
218                }
219            }
220            DatabaseErrorKind::TransactionFailed { message } => {
221                write!(f, "transaction_failed: {}", message)
222            }
223            DatabaseErrorKind::MigrationFailed { message } => {
224                write!(f, "migration_failed: {}", message)
225            }
226        }
227    }
228}
229
230/// WAE 错误类型
231#[derive(Debug, Clone, Serialize, Deserialize)]
232pub struct WaeError {
233    /// 错误类型
234    pub kind: ErrorKind,
235    /// 错误消息
236    pub message: Option<String>,
237    /// 附加参数
238    pub params: std::collections::HashMap<String, String>,
239}
240
241impl WaeError {
242    /// 创建新的错误
243    pub fn new(kind: ErrorKind) -> Self {
244        Self { kind, message: None, params: std::collections::HashMap::new() }
245    }
246
247    /// 创建验证错误
248    pub fn validation(kind: ValidationErrorKind) -> Self {
249        Self::new(ErrorKind::Validation).with_param("validation_kind", kind.to_string())
250    }
251
252    /// 创建验证错误(简单消息)
253    pub fn validation_message(message: impl Into<String>) -> Self {
254        Self::new(ErrorKind::Validation).with_message(message)
255    }
256
257    /// 创建网络错误
258    pub fn network(kind: NetworkErrorKind) -> Self {
259        Self::new(ErrorKind::Network).with_param("network_kind", kind.to_string())
260    }
261
262    /// 创建存储错误
263    pub fn storage(kind: StorageErrorKind) -> Self {
264        Self::new(ErrorKind::Storage).with_param("storage_kind", kind.to_string())
265    }
266
267    /// 创建数据库错误
268    pub fn database(kind: DatabaseErrorKind) -> Self {
269        Self::new(ErrorKind::Internal).with_param("database_kind", kind.to_string())
270    }
271
272    /// 创建内部错误
273    pub fn internal(message: impl Into<String>) -> Self {
274        Self::new(ErrorKind::Internal).with_message(message)
275    }
276
277    /// 创建未找到错误
278    pub fn not_found(resource: impl Into<String>) -> Self {
279        Self::new(ErrorKind::NotFound).with_param("resource", resource)
280    }
281
282    /// 创建权限错误
283    pub fn permission(action: impl Into<String>) -> Self {
284        Self::new(ErrorKind::Permission).with_param("action", action)
285    }
286
287    /// 创建超时错误
288    pub fn timeout(operation: impl Into<String>) -> Self {
289        Self::new(ErrorKind::Timeout).with_param("operation", operation)
290    }
291
292    /// 创建配置错误
293    pub fn config(message: impl Into<String>) -> Self {
294        Self::new(ErrorKind::Config).with_message(message)
295    }
296
297    /// 创建无效参数错误
298    pub fn invalid_params(message: impl Into<String>) -> Self {
299        Self::new(ErrorKind::Validation).with_message(message)
300    }
301
302    /// 设置错误消息
303    pub fn with_message(mut self, message: impl Into<String>) -> Self {
304        self.message = Some(message.into());
305        self
306    }
307
308    /// 添加参数
309    pub fn with_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
310        self.params.insert(key.into(), value.into());
311        self
312    }
313
314    /// 获取参数
315    pub fn get_param(&self, key: &str) -> Option<&String> {
316        self.params.get(key)
317    }
318}
319
320impl fmt::Display for WaeError {
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        match &self.message {
323            Some(msg) => write!(f, "{:?}: {}", self.kind, msg),
324            None => write!(f, "{:?}", self.kind),
325        }
326    }
327}
328
329impl std::error::Error for WaeError {}
330
331impl From<ValidationErrorKind> for WaeError {
332    fn from(kind: ValidationErrorKind) -> Self {
333        let message = match &kind {
334            ValidationErrorKind::InvalidFormat { field, expected } => {
335                format!("Invalid format for field '{}': expected {}", field, expected)
336            }
337            ValidationErrorKind::OutOfRange { field, min, max } => match (min, max) {
338                (Some(min), Some(max)) => format!("Field '{}' out of range: expected between {} and {}", field, min, max),
339                (Some(min), None) => format!("Field '{}' out of range: expected >= {}", field, min),
340                (None, Some(max)) => format!("Field '{}' out of range: expected <= {}", field, max),
341                (None, None) => format!("Field '{}' out of range", field),
342            },
343            ValidationErrorKind::Required { field } => format!("Field '{}' is required", field),
344            ValidationErrorKind::AlreadyExists { field, value } => {
345                format!("Field '{}' with value '{}' already exists", field, value)
346            }
347            ValidationErrorKind::NotAllowed { field, allowed } => {
348                format!("Field '{}' value not allowed. Allowed values: {:?}", field, allowed)
349            }
350            ValidationErrorKind::CustomValidation { field, message } => {
351                format!("Validation error for field '{}': {}", field, message)
352            }
353        };
354        Self::new(ErrorKind::Validation).with_message(message)
355    }
356}
357
358impl From<NetworkErrorKind> for WaeError {
359    fn from(kind: NetworkErrorKind) -> Self {
360        Self::network(kind)
361    }
362}
363
364impl From<StorageErrorKind> for WaeError {
365    fn from(kind: StorageErrorKind) -> Self {
366        Self::storage(kind)
367    }
368}
369
370impl From<DatabaseErrorKind> for WaeError {
371    fn from(kind: DatabaseErrorKind) -> Self {
372        Self::database(kind)
373    }
374}
375
376/// WAE 结果类型
377pub type WaeResult<T> = Result<T, WaeError>;
378
379/// 云服务错误类型
380#[derive(Debug, Clone, Serialize, Deserialize)]
381pub struct CloudError {
382    /// 错误代码
383    pub code: String,
384    /// 错误消息
385    pub message: String,
386    /// HTTP 状态码
387    pub status: Option<u16>,
388    /// 附加详情
389    pub details: Option<serde_json::Value>,
390}
391
392impl CloudError {
393    /// 创建新的云服务错误
394    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
395        Self { code: code.into(), message: message.into(), status: None, details: None }
396    }
397
398    /// 创建内部错误
399    pub fn internal(message: impl Into<String>) -> Self {
400        Self::new("INTERNAL_ERROR", message)
401    }
402
403    /// 创建无效参数错误
404    pub fn invalid_param(param: impl Into<String>, reason: impl Into<String>) -> Self {
405        Self::new("INVALID_PARAMETER", format!("Invalid parameter '{}': {}", param.into(), reason.into()))
406    }
407
408    /// 创建未找到错误
409    pub fn not_found(resource: impl Into<String>) -> Self {
410        Self::new("NOT_FOUND", format!("{} not found", resource.into()))
411    }
412
413    /// 创建权限错误
414    pub fn permission_denied(action: impl Into<String>) -> Self {
415        Self::new("PERMISSION_DENIED", format!("Permission denied for action: {}", action.into()))
416    }
417
418    /// 创建超时错误
419    pub fn timeout(operation: impl Into<String>) -> Self {
420        Self::new("TIMEOUT", format!("Operation timed out: {}", operation.into()))
421    }
422
423    /// 创建服务不可用错误
424    pub fn service_unavailable(service: impl Into<String>) -> Self {
425        Self::new("SERVICE_UNAVAILABLE", format!("Service unavailable: {}", service.into()))
426    }
427
428    /// 设置 HTTP 状态码
429    pub fn with_status(mut self, status: u16) -> Self {
430        self.status = Some(status);
431        self
432    }
433
434    /// 设置附加详情
435    pub fn with_details(mut self, details: serde_json::Value) -> Self {
436        self.details = Some(details);
437        self
438    }
439}
440
441impl fmt::Display for CloudError {
442    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
443        match self.status {
444            Some(status) => write!(f, "[{}] {} (HTTP {})", self.code, self.message, status),
445            None => write!(f, "[{}] {}", self.code, self.message),
446        }
447    }
448}
449
450impl std::error::Error for CloudError {}
451
452impl From<WaeError> for CloudError {
453    fn from(err: WaeError) -> Self {
454        CloudError::new(format!("{:?}", err.kind), err.message.unwrap_or_default())
455    }
456}
457
458/// 云服务结果类型
459pub type CloudResult<T> = Result<T, CloudError>;