Skip to main content

ncm_api_rs/
error.rs

1/// 错误类型定义
2use thiserror::Error;
3
4#[derive(Error, Debug)]
5pub enum NcmError {
6    /// HTTP 请求失败(网络错误、DNS 解析失败等)
7    #[error("HTTP request failed: {0}")]
8    Http(#[from] reqwest::Error),
9
10    /// API 业务错误(网易云返回非 200 状态码)
11    #[error("API error (code={code}): {msg}")]
12    Api { code: i64, msg: String },
13
14    /// 需要登录(API 返回 301)
15    #[error("Authentication required: {0}")]
16    AuthRequired(String),
17
18    /// 参数错误(缺少必要参数或格式不正确)
19    #[error("Invalid parameter: {0}")]
20    InvalidParam(String),
21
22    /// 加密/解密错误
23    #[error("Crypto error: {0}")]
24    Crypto(String),
25
26    /// JSON 序列化/反序列化错误
27    #[error("JSON error: {0}")]
28    Json(#[from] serde_json::Error),
29
30    /// 请求超时
31    #[error("Request timeout: {0}")]
32    Timeout(String),
33
34    /// 触发风控/限流(API 返回 503 或 IP 高频)
35    #[error("Rate limited: {0}")]
36    RateLimited(String),
37
38    /// 其他错误
39    #[error("{0}")]
40    Unknown(String),
41}
42
43impl NcmError {
44    /// 从 API 状态码和消息构造合适的错误类型
45    pub fn from_api(code: i64, msg: String) -> Self {
46        match code {
47            301 => NcmError::AuthRequired(if msg.is_empty() {
48                "需要登录".to_string()
49            } else {
50                msg
51            }),
52            400 => NcmError::InvalidParam(msg),
53            503 => NcmError::RateLimited(msg),
54            _ => NcmError::Api { code, msg },
55        }
56    }
57}
58
59pub type Result<T> = std::result::Result<T, NcmError>;