Skip to main content

lyrics_search/
error.rs

1//! 搜索与歌词获取的 crate 级错误类型。
2//!
3//! 各平台 Provider 与 [`Searcher`](crate::searchers::searcher::Searcher) 一律返回本类型,
4//! 调用方据此区分「没有这首歌」「被 captcha」「被限流」「网络不通」等失败原因,
5//! 而不必像 0.2.0 那样只能从一个 `None` 里猜。
6
7use std::fmt;
8
9/// 搜索或歌词获取过程中的错误。
10#[derive(Debug)]
11pub enum SearchError {
12    /// 网络请求失败:连接、超时、TLS,或响应体无法按目标类型解码(`reqwest::Error`)。
13    ///
14    /// 可用 `reqwest::Error::is_timeout` / `is_connect` / `is_decode` 进一步区分。
15    Http(reqwest::Error),
16    /// 响应文本不是合法 JSON(对响应文本调用 `serde_json` 时失败)。
17    Json(serde_json::Error),
18    /// 服务端返回了非成功状态码(4xx/5xx),例如 429 限流、401 凭证失效。
19    Status(u16),
20    /// 平台在 HTTP 成功响应里返回了业务层错误(如 QQ 音乐的 `code != 0`)。
21    Api(String),
22    /// 命中验证码风控(Musixmatch 401 + `captcha` hint),需要人工处理或更换配置。
23    Captcha,
24    /// 响应内容不符合预期格式(如 base64 / UTF-8 解码失败)。
25    Payload(String),
26    /// 传入的配置非法。
27    InvalidConfig(String),
28}
29
30impl fmt::Display for SearchError {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match self {
33            Self::Http(error) => write!(f, "HTTP 请求失败:{error}"),
34            Self::Json(error) => write!(f, "响应 JSON 解析失败:{error}"),
35            Self::Status(status) => write!(f, "服务端返回 HTTP {status}"),
36            Self::Api(message) => write!(f, "平台返回错误:{message}"),
37            Self::Captcha => write!(f, "命中验证码风控,需要人工处理"),
38            Self::Payload(message) => write!(f, "响应内容解析失败:{message}"),
39            Self::InvalidConfig(message) => write!(f, "配置非法:{message}"),
40        }
41    }
42}
43
44impl std::error::Error for SearchError {
45    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
46        match self {
47            Self::Http(error) => Some(error),
48            Self::Json(error) => Some(error),
49            _ => None,
50        }
51    }
52}
53
54impl From<reqwest::Error> for SearchError {
55    fn from(error: reqwest::Error) -> Self {
56        Self::Http(error)
57    }
58}
59
60impl From<serde_json::Error> for SearchError {
61    fn from(error: serde_json::Error) -> Self {
62        Self::Json(error)
63    }
64}