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 } => {
44                write!(f, "API error {}: {}", code, message)
45            }
46            TranslationError::ParseError(msg) => write!(f, "Parse error: {}", msg),
47        }
48    }
49}
50
51impl std::error::Error for TranslationError {}
52
53impl From<reqwest::Error> for TranslationError {
54    fn from(error: reqwest::Error) -> Self {
55        TranslationError::Http(error)
56    }
57}
58
59impl From<String> for TranslationError {
60    fn from(error: String) -> Self {
61        TranslationError::Custom(error)
62    }
63}
64
65impl From<&str> for TranslationError {
66    fn from(error: &str) -> Self {
67        TranslationError::Custom(error.to_string())
68    }
69}
70
71/// 翻译结果类型别名
72///
73/// 简化返回类型,使用 `TranslationError` 作为错误类型。
74///
75/// # 示例
76///
77/// ```rust
78/// use markdown_translator::{Result, TranslationError};
79///
80/// fn example_function() -> Result<String> {
81///     Ok("Success".to_string())
82/// }
83/// ```
84pub type Result<T> = std::result::Result<T, TranslationError>;