tushare_api/
error.rs

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