Skip to main content

longport/
error.rs

1use std::fmt::Display;
2
3use longport_httpcli::HttpClientError;
4use longport_wscli::WsClientError;
5use time::OffsetDateTime;
6
7/// LongPort OpenAPI SDK error type
8#[derive(Debug, thiserror::Error)]
9pub enum Error {
10    /// Decode Protobuf error
11    #[error(transparent)]
12    DecodeProtobuf(#[from] prost::DecodeError),
13
14    /// Decode JSON error
15    #[error(transparent)]
16    DecodeJSON(#[from] serde_json::Error),
17
18    /// Parse field
19    #[error("parse field: {name}: {error}")]
20    ParseField {
21        /// Field name
22        name: &'static str,
23
24        /// Error detail
25        error: String,
26    },
27
28    /// Unknown command
29    #[error("unknown command: {0}")]
30    UnknownCommand(
31        /// Command code
32        u8,
33    ),
34
35    /// Invalid security symbol
36    #[error("invalid security symbol: {symbol}")]
37    InvalidSecuritySymbol {
38        /// Security symbol
39        symbol: String,
40    },
41
42    /// Unknown market
43    #[error("unknown market: {symbol}")]
44    UnknownMarket {
45        /// Security symbol
46        symbol: String,
47    },
48
49    /// Unknown trade session
50    #[error("unknown trade session: {symbol}, time={time}")]
51    UnknownTradeSession {
52        /// Security symbol
53        symbol: String,
54        /// time
55        time: OffsetDateTime,
56    },
57
58    /// HTTP client error
59    #[error(transparent)]
60    HttpClient(#[from] HttpClientError),
61
62    /// Websocket client error
63    #[error(transparent)]
64    WsClient(#[from] WsClientError),
65
66    /// Blocking error
67    #[cfg(feature = "blocking")]
68    #[error(transparent)]
69    Blocking(#[from] crate::blocking::BlockingError),
70
71    /// OAuth error
72    #[error("oauth error: {0}")]
73    OAuth(#[from] longport_oauth::OAuthError),
74
75    /// A conversation event stream ended before a final result was observed
76    #[error("conversation stream ended before a final result was observed")]
77    ConversationStreamEnded,
78}
79
80impl Error {
81    #[inline]
82    pub(crate) fn parse_field_error(name: &'static str, error: impl Display) -> Self {
83        Self::ParseField {
84            name,
85            error: error.to_string(),
86        }
87    }
88
89    /// Returns the OpenAPI error code
90    pub fn openapi_error_code(&self) -> Option<i64> {
91        match self {
92            Error::HttpClient(HttpClientError::OpenApi { code, .. }) => Some(*code as i64),
93            Error::WsClient(WsClientError::ResponseError { detail, .. }) => {
94                detail.as_ref().map(|detail| detail.code as i64)
95            }
96            _ => None,
97        }
98    }
99
100    /// Consumes this error and returns a simple error
101    pub fn into_simple_error(self) -> SimpleError {
102        match self {
103            Error::HttpClient(HttpClientError::OpenApi {
104                code,
105                message,
106                trace_id,
107            }) => SimpleError::OpenApi {
108                code: code as i64,
109                message,
110                trace_id,
111            },
112            Error::HttpClient(HttpClientError::Http(err)) => {
113                if let Some(status) = err.0.status() {
114                    SimpleError::Http {
115                        status_code: status.as_u16(),
116                    }
117                } else {
118                    SimpleError::Other(err.to_string())
119                }
120            }
121            Error::HttpClient(HttpClientError::OAuth(err)) | Error::OAuth(err) => {
122                SimpleError::OAuth {
123                    code: err.code(),
124                    message: err.to_string(),
125                }
126            }
127            Error::WsClient(WsClientError::ResponseError {
128                detail: Some(detail),
129                ..
130            }) => SimpleError::OpenApi {
131                code: detail.code as i64,
132                message: detail.msg,
133                trace_id: String::new(),
134            },
135            Error::DecodeProtobuf(_)
136            | Error::DecodeJSON(_)
137            | Error::InvalidSecuritySymbol { .. }
138            | Error::UnknownMarket { .. }
139            | Error::UnknownTradeSession { .. }
140            | Error::ParseField { .. }
141            | Error::UnknownCommand(_)
142            | Error::HttpClient(_)
143            | Error::WsClient(_)
144            | Error::ConversationStreamEnded => SimpleError::Other(self.to_string()),
145            #[cfg(feature = "blocking")]
146            Error::Blocking(_) => SimpleError::Other(self.to_string()),
147        }
148    }
149}
150
151/// LongPort OpenAPI SDK result type
152pub type Result<T> = ::std::result::Result<T, Error>;
153
154/// Simple error type
155#[derive(Debug, thiserror::Error)]
156pub enum SimpleError {
157    /// Http error
158    #[error("http error: status_code={status_code}")]
159    Http {
160        /// HTTP status code
161        status_code: u16,
162    },
163    /// OpenAPI error
164    #[error("openapi error: code={code} message={message}")]
165    OpenApi {
166        /// Error code
167        code: i64,
168        /// Error message
169        message: String,
170        /// Trace id
171        trace_id: String,
172    },
173    /// Other error
174    #[error("other error: {0}")]
175    Other(String),
176    /// OAuth error
177    #[error("oauth error: {message}")]
178    OAuth {
179        /// Stable error code, see
180        /// [`OAuthError::code`](longport_oauth::OAuthError::code)
181        code: i64,
182        /// Error message
183        message: String,
184    },
185}
186
187impl From<Error> for SimpleError {
188    #[inline]
189    fn from(err: Error) -> Self {
190        err.into_simple_error()
191    }
192}
193
194/// Simple error kind
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum SimpleErrorKind {
197    /// HTTP error
198    Http,
199    /// OpenAPI error
200    OpenApi,
201    /// Other error
202    Other,
203    /// OAuth error
204    OAuth,
205}
206
207impl SimpleError {
208    /// Returns the kind of this error
209    pub fn kind(&self) -> SimpleErrorKind {
210        match self {
211            SimpleError::Http { .. } => SimpleErrorKind::Http,
212            SimpleError::OpenApi { .. } => SimpleErrorKind::OpenApi,
213            SimpleError::Other(_) => SimpleErrorKind::Other,
214            SimpleError::OAuth { .. } => SimpleErrorKind::OAuth,
215        }
216    }
217
218    /// Returns the error code
219    pub fn code(&self) -> Option<i64> {
220        match self {
221            SimpleError::Http { status_code } => Some(*status_code as i64),
222            SimpleError::OpenApi { code, .. } => Some(*code),
223            SimpleError::Other(_) => None,
224            SimpleError::OAuth { code, .. } => Some(*code),
225        }
226    }
227
228    /// Returns the trace id
229    pub fn trace_id(&self) -> Option<&str> {
230        match self {
231            SimpleError::Http { .. } => None,
232            SimpleError::OpenApi { trace_id, .. } => Some(trace_id),
233            SimpleError::Other(_) => None,
234            SimpleError::OAuth { .. } => None,
235        }
236    }
237
238    /// Returns the error message
239    pub fn message(&self) -> &str {
240        match self {
241            SimpleError::Http { .. } => "bad status code",
242            SimpleError::OpenApi { message, .. } => message.as_str(),
243            SimpleError::Other(message) => message.as_str(),
244            SimpleError::OAuth { message, .. } => message.as_str(),
245        }
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use longport_oauth::OAuthError;
252
253    use super::*;
254
255    #[test]
256    fn oauth_errors_keep_their_code() {
257        let err = Error::OAuth(OAuthError::NoTokenAvailable).into_simple_error();
258        assert_eq!(err.kind(), SimpleErrorKind::OAuth);
259        assert_eq!(err.code(), Some(1));
260        assert_eq!(err.message(), "no token available");
261
262        // A request that could not obtain a token reports the same code.
263        let err = Error::HttpClient(HttpClientError::OAuth(OAuthError::RevokeFailed {
264            message: "x".to_string(),
265        }))
266        .into_simple_error();
267        assert_eq!(err.kind(), SimpleErrorKind::OAuth);
268        assert_eq!(err.code(), Some(4));
269    }
270}