Skip to main content

fishpi_sdk/utils/
error.rs

1use std::error::Error as StdError;
2use std::time::Duration;
3use thiserror::Error;
4
5#[derive(Error, Debug)]
6#[non_exhaustive]
7pub enum Error {
8    /// 认证失败(token 失效/未登录)
9    #[error("未授权:请重新登录")]
10    Unauthorized,
11
12    /// 触发限流,`retry_after` 为服务端建议等待时长
13    #[error("请求过于频繁,请稍后再试")]
14    RateLimited { retry_after: Option<Duration> },
15
16    /// 资源不存在
17    #[error("资源不存在: {resource}")]
18    NotFound { resource: String },
19
20    /// 业务层错误:服务端返回非 0 `code`
21    #[error("业务错误[{code}]: {msg}")]
22    Business { code: i64, msg: String },
23
24    /// 传输层错误(连接/超时/TLS 等)
25    #[error("传输错误: {0}")]
26    Transport(#[from] reqwest::Error),
27
28    /// 反序列化/解析错误
29    #[error("解析错误: {0}")]
30    Decode(String),
31
32    /// WebSocket 连接/收发错误
33    #[error("WebSocket 错误: {0}")]
34    WebSocket(String),
35
36    #[error("Request error: {0}")]
37    Request(Box<dyn StdError + Send + Sync>),
38    #[error("{0}")]
39    Api(String),
40    #[error("Parse error: {0}")]
41    Parse(String),
42}
43
44impl Error {
45    /// 该错误是否值得重试
46    pub fn is_retryable(&self) -> bool {
47        matches!(
48            self,
49            Error::Transport(_) | Error::RateLimited { .. } | Error::Request(_)
50        )
51    }
52
53    pub fn business(code: i64, msg: impl Into<String>) -> Self {
54        Error::Business {
55            code,
56            msg: msg.into(),
57        }
58    }
59
60    pub fn decode(msg: impl Into<String>) -> Self {
61        Error::Decode(msg.into())
62    }
63}