Skip to main content

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}
28
29impl fmt::Display for WsError {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            Self::Connection(e) => write!(f, "WebSocket connection error: {e}"),
33            Self::MessageParse(e) => write!(f, "Failed to parse WebSocket message: {e}"),
34            Self::SubscriptionFailed(reason) => write!(f, "Subscription failed: {reason}"),
35            Self::AuthenticationFailed => write!(f, "WebSocket authentication failed"),
36            Self::ConnectionClosed => write!(f, "WebSocket connection closed"),
37            Self::Timeout => write!(f, "WebSocket operation timed out"),
38            Self::InvalidMessage(msg) => write!(f, "Invalid WebSocket message: {msg}"),
39        }
40    }
41}
42
43impl StdError for WsError {
44    fn source(&self) -> Option<&(dyn StdError + 'static)> {
45        match self {
46            Self::Connection(e) => Some(e),
47            Self::MessageParse(e) => Some(e),
48            _ => None,
49        }
50    }
51}
52
53// Integration with main Error type
54impl From<WsError> for crate::error::Error {
55    fn from(e: WsError) -> Self {
56        crate::error::Error::with_source(crate::error::Kind::WebSocket, e)
57    }
58}
59
60impl From<tokio_tungstenite::tungstenite::Error> for crate::error::Error {
61    fn from(e: tokio_tungstenite::tungstenite::Error) -> Self {
62        crate::error::Error::with_source(crate::error::Kind::WebSocket, WsError::Connection(e))
63    }
64}