tushare_api/
error.rs

1use std::fmt;
2use std::error::Error as StdError;
3
4/// Tushare API error types
5#[derive(Debug)]
6pub enum TushareError {
7    /// HTTP request error
8    HttpError(reqwest::Error),
9    /// API response error (contains error code and error message)
10    ApiError {
11        code: i32,
12        message: String,
13    },
14    /// JSON serialization/deserialization error
15    SerializationError(serde_json::Error),
16    /// Network timeout error
17    TimeoutError,
18    /// Invalid API Token
19    InvalidToken,
20    /// Data parsing error
21    ParseError(String),
22    /// Other errors
23    Other(String),
24}
25
26impl fmt::Display for TushareError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            TushareError::HttpError(err) => write!(f, "HTTP request error: {err}"),
30            TushareError::ApiError { code, message } => {
31                write!(f, "API error (code: {code}): {message}")
32            }
33            TushareError::SerializationError(err) => write!(f, "Serialization error: {err}"),
34            TushareError::TimeoutError => write!(f, "Request timeout"),
35            TushareError::InvalidToken => write!(f, "Invalid API Token"),
36            TushareError::ParseError(msg) => write!(f, "Parse error: {msg}"),
37            TushareError::Other(msg) => write!(f, "Other error: {msg}"),
38        }
39    }
40}
41
42impl StdError for TushareError {
43    fn source(&self) -> Option<&(dyn StdError + 'static)> {
44        match self {
45            TushareError::HttpError(err) => Some(err),
46            TushareError::SerializationError(err) => Some(err),
47            _ => None,
48        }
49    }
50}
51
52impl From<reqwest::Error> for TushareError {
53    fn from(err: reqwest::Error) -> Self {
54        if err.is_timeout() {
55            TushareError::TimeoutError
56        } else {
57            TushareError::HttpError(err)
58        }
59    }
60}
61
62impl From<serde_json::Error> for TushareError {
63    fn from(err: serde_json::Error) -> Self {
64        TushareError::SerializationError(err)
65    }
66}
67
68/// Tushare API result type
69pub type TushareResult<T> = Result<T, TushareError>;