Skip to main content

bybit_api/
error.rs

1//! Error types for the Bybit API client.
2
3use thiserror::Error;
4
5/// The main error type for the Bybit API client.
6///
7/// All fallible operations return `Result<T, BybitError>`.
8#[derive(Debug, Error)]
9pub enum BybitError {
10    /// HTTP request failed (network error, timeout, etc.)
11    #[error("HTTP error: {0}")]
12    Http(#[from] reqwest::Error),
13
14    /// WebSocket error
15    #[error("WebSocket error: {0}")]
16    WebSocket(Box<tokio_tungstenite::tungstenite::Error>),
17
18    /// Request timed out
19    #[error("Request timeout")]
20    Timeout,
21
22    /// Bybit API returned an error response
23    #[error("API error: code={code}, msg={msg}")]
24    Api {
25        /// Error code from Bybit API
26        code: i32,
27        /// Error message from Bybit API
28        msg: String,
29    },
30
31    /// Failed to parse response
32    #[error("Parse error: {0}")]
33    Parse(String),
34
35    /// Missing required field in response
36    #[error("Missing field: {0}")]
37    MissingField(&'static str),
38
39    /// Invalid parameter provided
40    #[error("Invalid parameter: {0}")]
41    InvalidParam(String),
42
43    /// Authentication error (missing or invalid credentials)
44    #[error("Authentication error: {0}")]
45    Auth(String),
46}
47
48/// Result type alias for Bybit operations
49pub type Result<T> = std::result::Result<T, BybitError>;
50
51impl BybitError {
52    /// Create an API error from code and message
53    pub fn api(code: i32, msg: impl Into<String>) -> Self {
54        Self::Api {
55            code,
56            msg: msg.into(),
57        }
58    }
59
60    /// Create a parse error
61    pub fn parse(msg: impl Into<String>) -> Self {
62        Self::Parse(msg.into())
63    }
64
65    /// Create an invalid parameter error
66    pub fn invalid_param(msg: impl Into<String>) -> Self {
67        Self::InvalidParam(msg.into())
68    }
69
70    /// Check if this is a rate limit error (code 10006)
71    pub fn is_rate_limited(&self) -> bool {
72        matches!(self, Self::Api { code: 10006, .. })
73    }
74
75    /// Check if this is a timeout error
76    pub fn is_timeout(&self) -> bool {
77        matches!(self, Self::Timeout)
78    }
79}