translation-lib 0.1.1

A simple and efficient translation library for Rust
Documentation
//! 错误处理模块
//!
//! 定义翻译库中使用的简化错误类型和错误处理机制。

use std::fmt;

/// 翻译错误类型
///
/// 简化的错误类型,包含翻译过程中的主要错误情况。
#[derive(Debug, Clone)]
pub enum TranslationError {
    /// 配置错误
    Config(String),

    /// 网络错误
    Network(String),

    /// API错误
    Api(String),

    /// 解析错误
    Parse(String),

    /// 频率限制错误
    RateLimit,
}

impl fmt::Display for TranslationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TranslationError::Config(msg) => write!(f, "Configuration error: {}", msg),
            TranslationError::Network(msg) => write!(f, "Network error: {}", msg),
            TranslationError::Api(msg) => write!(f, "API error: {}", msg),
            TranslationError::Parse(msg) => write!(f, "Parse error: {}", msg),
            TranslationError::RateLimit => write!(f, "Rate limit exceeded"),
        }
    }
}

impl std::error::Error for TranslationError {}

impl From<reqwest::Error> for TranslationError {
    fn from(error: reqwest::Error) -> Self {
        if error.is_timeout() {
            TranslationError::Network("Request timeout".to_string())
        } else if error.is_connect() {
            TranslationError::Network("Connection failed".to_string())
        } else {
            TranslationError::Network(error.to_string())
        }
    }
}

impl From<String> for TranslationError {
    fn from(error: String) -> Self {
        TranslationError::Api(error)
    }
}

impl From<&str> for TranslationError {
    fn from(error: &str) -> Self {
        TranslationError::Api(error.to_string())
    }
}

/// 翻译结果类型别名
pub type TranslationResult<T> = std::result::Result<T, TranslationError>;

/// 判断错误是否可以重试
impl TranslationError {
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            TranslationError::Network(_) | TranslationError::RateLimit
        )
    }

    /// 获取建议的重试延迟时间(毫秒)
    pub fn retry_delay_ms(&self) -> Option<u64> {
        match self {
            TranslationError::Network(_) => Some(1000), // 1秒
            TranslationError::RateLimit => Some(5000),  // 5秒
            _ => None,
        }
    }
}