agentlink-core 0.1.0

AgentLink SDK Core - Platform agnostic core library
Documentation
//! SDK Error Types

use thiserror::Error;

/// SDK 错误类型
#[derive(Error, Debug, Clone)]
pub enum SdkError {
    /// HTTP 请求错误
    #[error("HTTP error: {0}")]
    Http(String),

    /// MQTT 错误
    #[error("MQTT error: {0}")]
    Mqtt(String),

    /// 序列化/反序列化错误
    #[error("Serialization error: {0}")]
    Serialization(String),

    /// 认证错误
    #[error("Authentication error: {0}")]
    Auth(String),

    /// 网络错误
    #[error("Network error: {0}")]
    Network(String),

    /// 配置错误
    #[error("Configuration error: {0}")]
    Config(String),

    /// 未连接
    #[error("Not connected")]
    NotConnected,

    /// 超时
    #[error("Timeout")]
    Timeout,

    /// 其他错误
    #[error("Other error: {0}")]
    Other(String),
}

/// SDK 结果类型
pub type SdkResult<T> = Result<T, SdkError>;



impl From<serde_json::Error> for SdkError {
    fn from(err: serde_json::Error) -> Self {
        SdkError::Serialization(err.to_string())
    }
}

impl From<std::io::Error> for SdkError {
    fn from(err: std::io::Error) -> Self {
        SdkError::Network(err.to_string())
    }
}

/// HTTP 错误类型
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HttpErrorType {
    /// 未授权 (401)
    Unauthorized,
    /// 禁止访问 (403)
    Forbidden,
    /// 未找到 (404)
    NotFound,
    /// 请求错误 (400)
    BadRequest,
    /// 服务器错误 (5xx)
    ServerError,
    /// 网络错误
    NetworkError,
    /// 其他错误
    Other,
}

/// 结构化的 HTTP 错误
#[derive(Debug, Clone)]
pub struct HttpError {
    /// 错误类型
    pub error_type: HttpErrorType,
    /// HTTP 状态码
    pub status_code: u16,
    /// 错误消息
    pub message: String,
    /// 是否需要重新登录
    pub requires_relogin: bool,
}

impl HttpError {
    /// 从错误字符串解析
    pub fn from_error(error: &str, default_message: &str) -> Self {
        // 优先检查服务端返回的结构化错误(格式: "CODE: Message")
        if let Some(colon_pos) = error.find(':') {
            let code = &error[..colon_pos];
            let message = error[colon_pos + 1..].trim();

            // 只处理全大写的错误码
            if code.chars().all(|c| c.is_ascii_uppercase() || c == '_') {
                match code {
                    "USER_NOT_FOUND" | "USER_DELETED" => {
                        return Self {
                            error_type: HttpErrorType::NotFound,
                            status_code: 404,
                            message: message.to_string(),
                            requires_relogin: true,
                        };
                    }
                    "INVALID_TOKEN" | "TOKEN_EXPIRED" => {
                        return Self {
                            error_type: HttpErrorType::Unauthorized,
                            status_code: 401,
                            message: message.to_string(),
                            requires_relogin: true,
                        };
                    }
                    "UNAUTHORIZED" | "AUTH_FAILED" => {
                        return Self {
                            error_type: HttpErrorType::Unauthorized,
                            status_code: 401,
                            message: message.to_string(),
                            requires_relogin: true,
                        };
                    }
                    "FORBIDDEN" => {
                        return Self {
                            error_type: HttpErrorType::Forbidden,
                            status_code: 403,
                            message: message.to_string(),
                            requires_relogin: false,
                        };
                    }
                    _ => {}
                }
            }
        }

        // 回退:尝试从错误消息中提取状态码和关键词
        if error.contains("HTTP 错误: 401") || error.contains("HTTP 401") {
            Self {
                error_type: HttpErrorType::Unauthorized,
                status_code: 401,
                message: "登录已过期,请重新登录".to_string(),
                requires_relogin: true,
            }
        } else if error.contains("HTTP 错误: 403") || error.contains("HTTP 403") {
            Self {
                error_type: HttpErrorType::Forbidden,
                status_code: 403,
                message: "无权限访问此资源".to_string(),
                requires_relogin: false,
            }
        } else if error.contains("HTTP 错误: 404") || error.contains("HTTP 404") {
            Self {
                error_type: HttpErrorType::NotFound,
                status_code: 404,
                message: "资源不存在".to_string(),
                requires_relogin: false,
            }
        } else if error.contains("HTTP 错误: 400") || error.contains("HTTP 400") {
            Self {
                error_type: HttpErrorType::BadRequest,
                status_code: 400,
                message: "请求参数错误".to_string(),
                requires_relogin: false,
            }
        } else if error.contains("HTTP 错误: 5") || error.contains("HTTP 50") {
            Self {
                error_type: HttpErrorType::ServerError,
                status_code: 500,
                message: "服务器错误,请稍后重试".to_string(),
                requires_relogin: false,
            }
        } else {
            Self {
                error_type: HttpErrorType::Other,
                status_code: 0,
                message: if default_message.is_empty() {
                    error.to_string()
                } else {
                    format!("{}: {}", default_message, error)
                },
                requires_relogin: false,
            }
        }
    }
}