Skip to main content

ds_api/
error.rs

1//! 统一的错误类型
2//!
3//! 该模块使用 `thiserror` 提供库内部统一的 `ApiError` 类型并导出通用 `Result<T>` 别名。
4//! 目标:把库中散落的各种错误(例如 `Box<dyn Error>`、`reqwest::Error`、`serde_json::Error`)统一到一个基于 `thiserror` 的 `ApiError`,并导出便捷的 `Result<T>` 别名,方便 `?` 自动转换与更友好的错误展示。
5
6use thiserror::Error;
7
8/// 统一的错误类型,覆盖常见的错误来源并保留一个通用字符串变体用于快速转换。
9#[derive(Error, Debug)]
10pub enum ApiError {
11    /// HTTP 层面的失败(当我们想保留状态码与响应文本时使用)
12    #[error("HTTP error {status}: {text}")]
13    Http {
14        status: reqwest::StatusCode,
15        text: String,
16    },
17
18    /// reqwest 网络/请求错误
19    #[error("Reqwest error: {0}")]
20    Reqwest(#[from] reqwest::Error),
21
22    /// serde_json 解析/序列化错误
23    #[error("JSON error: {0}")]
24    Json(#[from] serde_json::Error),
25
26    /// EventSource / SSE 处理错误(来自 `eventsource-stream` crate)
27    /// 以字符串形式保存错误信息(避免直接依赖具体 crate 的错误类型签名)
28    #[error("EventSource error: {0}")]
29    EventSource(String),
30
31    /// IO 错误(保底)
32    #[error("IO error: {0}")]
33    Io(#[from] std::io::Error),
34
35    /// 通用字符串错误(方便从 `String` / `&str` 直接转换)
36    #[error("{0}")]
37    Other(String),
38
39    /// 未知或占位错误
40    #[error("Unknown error")]
41    Unknown,
42}
43
44/// 常用的 `Result` 别名,方便在库内统一返回类型。
45pub type Result<T> = std::result::Result<T, ApiError>;
46
47impl ApiError {
48    /// 创建一个 `Http` 变体的快捷方法
49    pub fn http_error(status: reqwest::StatusCode, text: impl Into<String>) -> Self {
50        ApiError::Http {
51            status,
52            text: text.into(),
53        }
54    }
55}
56
57impl From<&str> for ApiError {
58    fn from(s: &str) -> Self {
59        ApiError::Other(s.to_string())
60    }
61}
62
63impl From<String> for ApiError {
64    fn from(s: String) -> Self {
65        ApiError::Other(s)
66    }
67}