markdown_translator/
error.rs

1//! 错误处理模块
2//! 
3//! 定义翻译库中使用的错误类型和错误处理机制。
4
5use std::fmt;
6
7/// 翻译错误类型
8/// 
9/// 包含翻译过程中可能出现的各种错误情况。
10/// 
11/// # 变体说明
12/// 
13/// * `Http` - HTTP请求错误
14/// * `Custom` - 自定义错误消息
15/// * `RateLimitError` - 速率限制错误
16/// * `ApiError` - API响应错误,包含错误代码和消息
17/// * `ParseError` - 解析错误
18#[derive(Debug)]
19pub enum TranslationError {
20    /// HTTP请求错误
21    Http(reqwest::Error),
22    /// 自定义错误消息
23    Custom(String),
24    /// 速率限制错误
25    RateLimitError(String),
26    /// API响应错误
27    ApiError { 
28        /// 错误代码
29        code: i32, 
30        /// 错误消息
31        message: String 
32    },
33    /// 解析错误
34    ParseError(String),
35}
36
37impl fmt::Display for TranslationError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match self {
40            TranslationError::Http(e) => write!(f, "HTTP error: {}", e),
41            TranslationError::Custom(msg) => write!(f, "{}", msg),
42            TranslationError::RateLimitError(msg) => write!(f, "Rate limit error: {}", msg),
43            TranslationError::ApiError { code, message } => write!(f, "API error {}: {}", code, message),
44            TranslationError::ParseError(msg) => write!(f, "Parse error: {}", msg),
45        }
46    }
47}
48
49impl std::error::Error for TranslationError {}
50
51impl From<reqwest::Error> for TranslationError {
52    fn from(error: reqwest::Error) -> Self {
53        TranslationError::Http(error)
54    }
55}
56
57impl From<String> for TranslationError {
58    fn from(error: String) -> Self {
59        TranslationError::Custom(error)
60    }
61}
62
63impl From<&str> for TranslationError {
64    fn from(error: &str) -> Self {
65        TranslationError::Custom(error.to_string())
66    }
67}
68
69/// 翻译结果类型别名
70/// 
71/// 简化返回类型,使用 `TranslationError` 作为错误类型。
72/// 
73/// # 示例
74/// 
75/// ```rust
76/// use markdown_translator::{Result, TranslationError};
77/// 
78/// fn example_function() -> Result<String> {
79///     Ok("Success".to_string())
80/// }
81/// ```
82pub type Result<T> = std::result::Result<T, TranslationError>;