Skip to main content

plexus_client/
error.rs

1//! The two error layers a Plexus client sees, kept apart by type.
2//!
3//! The wire has two independent failure modes and conflating them is the
4//! bug this split exists to prevent:
5//!
6//! | Layer | Meaning | Type |
7//! |---|---|---|
8//! | transport | the connection/HTTP call failed; nothing was said about the request | [`TransportError`] |
9//! | in-band | the server answered, and the answer is an `error` item | [`ClientError::Remote`] |
10//!
11//! `menger/web/index.html` distinguishes these by depth
12//! (`item.type === "error"` vs `item.content.type === "error"`); here the
13//! distinction is in the type system instead.
14
15use std::fmt;
16
17/// What kind of transport failure occurred.
18#[derive(Debug, Clone, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum TransportErrorKind {
21    /// Could not establish the connection at all.
22    Connect,
23    /// The peer spoke something this transport could not parse (a malformed
24    /// JSON-RPC frame, an SSE frame with no `data:` line that was required,
25    /// a JSON-RPC `error` response to the subscribe call).
26    Protocol,
27    /// A non-success HTTP status.
28    Http { status: u16 },
29    /// The stream ended without a terminal item.
30    Closed,
31    /// Anything the transport wants to report that is none of the above.
32    Other,
33}
34
35/// A failure of the transport itself — the request never got an answer, or
36/// the answer was unintelligible.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct TransportError {
39    pub kind: TransportErrorKind,
40    pub message: String,
41}
42
43impl TransportError {
44    pub fn new(kind: TransportErrorKind, message: impl Into<String>) -> Self {
45        Self {
46            kind,
47            message: message.into(),
48        }
49    }
50    pub fn connect(message: impl Into<String>) -> Self {
51        Self::new(TransportErrorKind::Connect, message)
52    }
53    pub fn protocol(message: impl Into<String>) -> Self {
54        Self::new(TransportErrorKind::Protocol, message)
55    }
56    pub fn http(status: u16, message: impl Into<String>) -> Self {
57        Self::new(TransportErrorKind::Http { status }, message)
58    }
59    pub fn closed(message: impl Into<String>) -> Self {
60        Self::new(TransportErrorKind::Closed, message)
61    }
62    pub fn other(message: impl Into<String>) -> Self {
63        Self::new(TransportErrorKind::Other, message)
64    }
65}
66
67impl fmt::Display for TransportError {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        match self.kind {
70            TransportErrorKind::Connect => write!(f, "transport connect: {}", self.message),
71            TransportErrorKind::Protocol => write!(f, "transport protocol: {}", self.message),
72            TransportErrorKind::Http { status } => {
73                write!(f, "transport http {}: {}", status, self.message)
74            }
75            TransportErrorKind::Closed => write!(f, "transport closed: {}", self.message),
76            TransportErrorKind::Other => write!(f, "transport: {}", self.message),
77        }
78    }
79}
80
81impl std::error::Error for TransportError {}
82
83/// Everything that can go wrong on a typed client call.
84#[derive(Debug, Clone, PartialEq)]
85#[non_exhaustive]
86pub enum ClientError {
87    /// The transport failed. See [`TransportError`].
88    Transport(TransportError),
89
90    /// The server answered with an in-band `error` item. This is the
91    /// activation or the hub saying no — the transport worked fine.
92    Remote {
93        message: String,
94        code: Option<String>,
95        recoverable: bool,
96    },
97
98    /// A `data` item arrived whose `content` did not deserialize into the
99    /// method's event type. This is a contract break between client and
100    /// server (a renamed field, a version skew) and terminates the stream.
101    Decode {
102        /// The item's `content_type`, when the transport carried one.
103        content_type: Option<String>,
104        message: String,
105    },
106
107    /// An argument could not be serialized into the call's params object,
108    /// so nothing was sent. A generated client reports this rather than
109    /// panicking — a panic in a wasm32 consumer is an unrecoverable trap.
110    Encode {
111        /// The parameter that failed.
112        param: &'static str,
113        message: String,
114    },
115}
116
117impl ClientError {
118    /// `true` when the failure came from the transport rather than the peer.
119    pub fn is_transport(&self) -> bool {
120        matches!(self, ClientError::Transport(_))
121    }
122    /// `true` when the peer answered with an in-band `error` item.
123    pub fn is_remote(&self) -> bool {
124        matches!(self, ClientError::Remote { .. })
125    }
126}
127
128impl From<TransportError> for ClientError {
129    fn from(e: TransportError) -> Self {
130        ClientError::Transport(e)
131    }
132}
133
134impl fmt::Display for ClientError {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        match self {
137            ClientError::Transport(e) => write!(f, "{e}"),
138            ClientError::Remote {
139                message,
140                code: Some(code),
141                ..
142            } => write!(f, "remote error [{code}]: {message}"),
143            ClientError::Remote { message, .. } => write!(f, "remote error: {message}"),
144            ClientError::Decode {
145                content_type: Some(ct),
146                message,
147            } => write!(f, "decode {ct}: {message}"),
148            ClientError::Decode { message, .. } => write!(f, "decode: {message}"),
149            ClientError::Encode { param, message } => {
150                write!(f, "encode param `{param}`: {message}")
151            }
152        }
153    }
154}
155
156impl std::error::Error for ClientError {}