polymarket_client_sdk/ws/
error.rs

1#![expect(
2    clippy::module_name_repetitions,
3    reason = "Error types include the module name to indicate their scope"
4)]
5
6use std::error::Error as StdError;
7use std::fmt;
8
9/// WebSocket error variants.
10#[non_exhaustive]
11#[derive(Debug)]
12pub enum WsError {
13    /// Error connecting to or communicating with the WebSocket server
14    Connection(tokio_tungstenite::tungstenite::Error),
15    /// Error parsing a WebSocket message
16    MessageParse(serde_json::Error),
17    /// Subscription request failed
18    SubscriptionFailed(String),
19    /// Authentication failed for authenticated channel
20    AuthenticationFailed,
21    /// WebSocket connection was closed
22    ConnectionClosed,
23    /// Operation timed out
24    Timeout,
25    /// Received an invalid or unexpected message
26    InvalidMessage(String),
27    /// Subscription stream lagged and missed messages
28    Lagged {
29        /// Number of messages that were missed
30        count: u64,
31    },
32}
33
34impl fmt::Display for WsError {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        match self {
37            Self::Connection(e) => write!(f, "WebSocket connection error: {e}"),
38            Self::MessageParse(e) => write!(f, "Failed to parse WebSocket message: {e}"),
39            Self::SubscriptionFailed(reason) => write!(f, "Subscription failed: {reason}"),
40            Self::AuthenticationFailed => write!(f, "WebSocket authentication failed"),
41            Self::ConnectionClosed => write!(f, "WebSocket connection closed"),
42            Self::Timeout => write!(f, "WebSocket operation timed out"),
43            Self::InvalidMessage(msg) => write!(f, "Invalid WebSocket message: {msg}"),
44            Self::Lagged { count } => write!(f, "Subscription lagged, missed {count} messages"),
45        }
46    }
47}
48
49impl StdError for WsError {
50    fn source(&self) -> Option<&(dyn StdError + 'static)> {
51        match self {
52            Self::Connection(e) => Some(e),
53            Self::MessageParse(e) => Some(e),
54            _ => None,
55        }
56    }
57}
58
59// Integration with main Error type
60impl From<WsError> for crate::error::Error {
61    fn from(e: WsError) -> Self {
62        crate::error::Error::with_source(crate::error::Kind::WebSocket, e)
63    }
64}
65
66impl From<tokio_tungstenite::tungstenite::Error> for crate::error::Error {
67    fn from(e: tokio_tungstenite::tungstenite::Error) -> Self {
68        crate::error::Error::with_source(crate::error::Kind::WebSocket, WsError::Connection(e))
69    }
70}