Skip to main content

tauri_plugin_socketio/
error.rs

1use serde::{Serialize, Serializer};
2use serde_json::{Value, json};
3use socketio_next::engineio;
4
5/// Errors of the plugin. Over the IPC they become `{ kind, message, data? }` (see
6/// [`ErrorPayload`]); guest-js throws them as `SocketIoError`.
7#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum Error {
10    /// The socket.io client failed (connect, emit, ack timeout, ...).
11    #[error(transparent)]
12    SocketIo(#[from] socketio_next::Error),
13    /// No client is registered under this id.
14    #[error("no socket.io client with id `{0}`")]
15    UnknownClient(String),
16    /// A client is registered under this id already (remove it first).
17    #[error("a socket.io client with id `{0}` is registered already")]
18    AlreadyExists(String),
19    /// The client is [`Access::ReadOnly`](crate::Access::ReadOnly): the webview may not emit,
20    /// ack or disconnect it.
21    #[error("socket.io client `{0}` is read-only for the webview")]
22    AccessDenied(String),
23    /// The server ack was answered already, expired, or was not offered to this webview.
24    #[error("no pending server ack {0} for this webview (answered, expired or unknown)")]
25    UnknownAck(u64),
26    /// Rust reserved this id ([`SocketIo::reserve`](crate::SocketIo::reserve)): the webview may
27    /// not connect a client under it.
28    #[error("the id `{0}` is reserved for a client registered from Rust")]
29    Reserved(String),
30    /// The URL is outside the plugin's allow-list ([`Builder::allow_url_prefix`](crate::Builder::allow_url_prefix)).
31    #[error("the server URL is not allowed by the socketio plugin configuration")]
32    UrlNotAllowed,
33    /// The webview has [`MAX_SUBSCRIPTIONS_PER_WEBVIEW`](crate::MAX_SUBSCRIPTIONS_PER_WEBVIEW)
34    /// subscriptions already.
35    #[error("too many socket.io subscriptions for this webview (at most {0})")]
36    TooManySubscriptions(usize),
37    /// The webview has [`MAX_CLIENTS_PER_WEBVIEW`](crate::MAX_CLIENTS_PER_WEBVIEW) clients it
38    /// connected already.
39    #[error("too many socket.io clients connected by this webview (at most {0})")]
40    TooManyClients(usize),
41    /// `setAuth` / `setHeaders` / `setQuery` on a client the webview did not connect (Rust
42    /// built it; Rust decides what it sends).
43    #[error("socket.io client `{0}` was registered from Rust: its connect values are Rust's")]
44    NotConfigurable(String),
45    /// A connect option or argument has the wrong type or value (the value itself is not shown).
46    #[error("invalid options: {0}")]
47    InvalidOptions(String),
48}
49
50/// Result alias of the plugin.
51pub type Result<T> = std::result::Result<T, Error>;
52
53/// An error as JS sees it: `kind` is the variant name (`ConnectRejected`, `NotConnected`,
54/// `AckTimeout`, `ConnectTimeout`, `AccessDenied`, `UnknownClient`, ..., engine.io failures by
55/// their own name such as `HttpStatus` or `TlsProviderMissing`), `message` the text (never a
56/// URL or query value), `data` extra fields (`ConnectRejected`: the server's `err.data`;
57/// `HttpStatus`: `{ status, message }`; `WebsocketClosed`: `{ code, reason }`).
58#[derive(Debug, Clone, PartialEq, Serialize)]
59pub struct ErrorPayload {
60    /// The variant name.
61    pub kind: &'static str,
62    /// The message.
63    pub message: String,
64    /// Extra data, if any.
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub data: Option<Value>,
67}
68
69impl ErrorPayload {
70    pub(crate) fn from_core(err: &socketio_next::Error) -> Self {
71        use socketio_next::Error as E;
72        let mut data = None;
73        let kind = match err {
74            E::InvalidUrl(_) => "InvalidUrl",
75            E::Engine(e) => engine_kind(e, &mut data),
76            E::Protocol(_) => "Protocol",
77            E::ConnectTimeout(_) => "ConnectTimeout",
78            E::ConnectRejected { data: d, .. } => {
79                data.clone_from(d);
80                "ConnectRejected"
81            }
82            E::IncompatibleServer => "IncompatibleServer",
83            E::InvalidAuth(_) => "InvalidAuth",
84            E::NotConnected => "NotConnected",
85            E::Closed => "Closed",
86            E::AckTimeout(_) => "AckTimeout",
87            E::Disconnected => "Disconnected",
88            E::ReservedEvent(_) => "ReservedEvent",
89            E::Json(_) => "Json",
90            E::InvalidHeader(_) => "InvalidHeader",
91            _ => "SocketIo",
92        };
93        ErrorPayload {
94            kind,
95            message: err.to_string(),
96            data,
97        }
98    }
99}
100
101fn engine_kind(err: &engineio::Error, data: &mut Option<Value>) -> &'static str {
102    use engineio::Error as E;
103    match err {
104        E::Protocol(_) => "Protocol",
105        E::InvalidUrl(_) => "InvalidUrl",
106        E::InvalidUrlScheme(_) => "InvalidUrlScheme",
107        E::Http(_) => "Http",
108        E::HttpStatus {
109            status, message, ..
110        } => {
111            *data = Some(json!({ "status": status, "message": message }));
112            "HttpStatus"
113        }
114        E::WebsocketClosed { code, reason, .. } => {
115            *data = Some(json!({ "code": code, "reason": reason }));
116            "WebsocketClosed"
117        }
118        E::ProxyFailed(_) => "ProxyFailed",
119        E::Websocket(_) => "Websocket",
120        E::InvalidHandshake(_) => "InvalidHandshake",
121        E::NotConnected => "NotConnected",
122        E::UpgradeUnavailable => "UpgradeUnavailable",
123        E::UpgradeFailed(_) => "UpgradeFailed",
124        E::PingTimeout => "PingTimeout",
125        E::Timeout(_) => "Timeout",
126        E::TlsNotEnabled(_) => "TlsNotEnabled",
127        E::TlsProviderMissing => "TlsProviderMissing",
128        E::InvalidTlsConfig(_) => "InvalidTlsConfig",
129        _ => "Engine",
130    }
131}
132
133impl From<&Error> for ErrorPayload {
134    fn from(err: &Error) -> Self {
135        let kind = match err {
136            Error::SocketIo(e) => return ErrorPayload::from_core(e),
137            Error::UnknownClient(_) => "UnknownClient",
138            Error::AlreadyExists(_) => "AlreadyExists",
139            Error::AccessDenied(_) => "AccessDenied",
140            Error::UnknownAck(_) => "UnknownAck",
141            Error::Reserved(_) => "Reserved",
142            Error::UrlNotAllowed => "UrlNotAllowed",
143            Error::TooManySubscriptions(_) => "TooManySubscriptions",
144            Error::TooManyClients(_) => "TooManyClients",
145            Error::InvalidOptions(_) => "InvalidOptions",
146            Error::NotConfigurable(_) => "NotConfigurable",
147        };
148        ErrorPayload {
149            kind,
150            message: err.to_string(),
151            data: None,
152        }
153    }
154}
155
156impl Serialize for Error {
157    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
158        ErrorPayload::from(self).serialize(serializer)
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    /// Plugin errors here; socketio-next's (`ConnectRejected`, `HttpStatus`,
167    /// `WebsocketClosed`) come from real servers in the IPC tests.
168    #[test]
169    fn kinds_and_data() {
170        let denied = serde_json::to_value(Error::AccessDenied("core".into())).unwrap();
171        assert_eq!(denied["kind"], "AccessDenied");
172        assert!(denied.get("data").is_none());
173        let not =
174            serde_json::to_value(Error::SocketIo(socketio_next::Error::NotConnected)).unwrap();
175        assert_eq!(not["kind"], "NotConnected");
176    }
177}