rust_cnb/
error.rs

1//! 错误处理
2
3use std::fmt;
4
5/// API 错误类型
6#[derive(Debug)]
7pub enum ApiError {
8    /// HTTP 请求错误
9    RequestError(reqwest::Error),
10    /// HTTP 状态码错误
11    HttpError(u16),
12    /// URL 解析错误
13    UrlError(url::ParseError),
14    /// JSON 序列化/反序列化错误
15    JsonError(serde_json::Error),
16}
17
18impl fmt::Display for ApiError {
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            ApiError::RequestError(e) => write!(f, "请求错误: {}", e),
22            ApiError::HttpError(status) => write!(f, "HTTP 错误: {}", status),
23            ApiError::UrlError(e) => write!(f, "URL 解析错误: {}", e),
24            ApiError::JsonError(e) => write!(f, "JSON 错误: {}", e),
25        }
26    }
27}
28
29impl std::error::Error for ApiError {}
30
31impl From<reqwest::Error> for ApiError {
32    fn from(error: reqwest::Error) -> Self {
33        ApiError::RequestError(error)
34    }
35}
36
37impl From<url::ParseError> for ApiError {
38    fn from(error: url::ParseError) -> Self {
39        ApiError::UrlError(error)
40    }
41}
42
43impl From<serde_json::Error> for ApiError {
44    fn from(error: serde_json::Error) -> Self {
45        ApiError::JsonError(error)
46    }
47}
48
49/// 结果类型别名
50pub type Result<T> = std::result::Result<T, ApiError>;