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    /// `setAuth` / `setHeaders` / `setQuery` on a client the webview did not connect (Rust
38    /// built it; Rust decides what it sends).
39    #[error("socket.io client `{0}` was registered from Rust: its connect values are Rust's")]
40    NotConfigurable(String),
41    /// A connect option or argument has the wrong type or value (the value itself is not shown).
42    #[error("invalid options: {0}")]
43    InvalidOptions(String),
44}
45
46/// Result alias of the plugin.
47pub type Result<T> = std::result::Result<T, Error>;
48
49/// An error as JS sees it: `kind` is the variant name (`ConnectRejected`, `NotConnected`,
50/// `AckTimeout`, `ConnectTimeout`, `AccessDenied`, `UnknownClient`, ..., engine.io failures by
51/// their own name such as `HttpStatus` or `TlsProviderMissing`), `message` the text (never a
52/// URL or query value), `data` extra fields (`ConnectRejected`: the server's `err.data`;
53/// `HttpStatus`: `{ status, message }`; `WebsocketClosed`: `{ code, reason }`).
54#[derive(Debug, Clone, PartialEq, Serialize)]
55pub struct ErrorPayload {
56    /// The variant name.
57    pub kind: &'static str,
58    /// The message.
59    pub message: String,
60    /// Extra data, if any.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub data: Option<Value>,
63}
64
65impl ErrorPayload {
66    pub(crate) fn from_core(err: &socketio_next::Error) -> Self {
67        use socketio_next::Error as E;
68        let mut data = None;
69        let kind = match err {
70            E::InvalidUrl(_) => "InvalidUrl",
71            E::Engine(e) => engine_kind(e, &mut data),
72            E::Protocol(_) => "Protocol",
73            E::ConnectTimeout(_) => "ConnectTimeout",
74            E::ConnectRejected { data: d, .. } => {
75                data.clone_from(d);
76                "ConnectRejected"
77            }
78            E::IncompatibleServer => "IncompatibleServer",
79            E::InvalidAuth(_) => "InvalidAuth",
80            E::NotConnected => "NotConnected",
81            E::Closed => "Closed",
82            E::AckTimeout(_) => "AckTimeout",
83            E::Disconnected => "Disconnected",
84            E::ReservedEvent(_) => "ReservedEvent",
85            E::Json(_) => "Json",
86            E::InvalidHeader(_) => "InvalidHeader",
87            _ => "SocketIo",
88        };
89        ErrorPayload {
90            kind,
91            message: err.to_string(),
92            data,
93        }
94    }
95}
96
97fn engine_kind(err: &engineio::Error, data: &mut Option<Value>) -> &'static str {
98    use engineio::Error as E;
99    match err {
100        E::Protocol(_) => "Protocol",
101        E::InvalidUrl(_) => "InvalidUrl",
102        E::InvalidUrlScheme(_) => "InvalidUrlScheme",
103        E::Http(_) => "Http",
104        E::HttpStatus {
105            status, message, ..
106        } => {
107            *data = Some(json!({ "status": status, "message": message }));
108            "HttpStatus"
109        }
110        E::WebsocketClosed { code, reason, .. } => {
111            *data = Some(json!({ "code": code, "reason": reason }));
112            "WebsocketClosed"
113        }
114        E::ProxyFailed(_) => "ProxyFailed",
115        E::Websocket(_) => "Websocket",
116        E::InvalidHandshake(_) => "InvalidHandshake",
117        E::NotConnected => "NotConnected",
118        E::UpgradeUnavailable => "UpgradeUnavailable",
119        E::UpgradeFailed(_) => "UpgradeFailed",
120        E::PingTimeout => "PingTimeout",
121        E::Timeout(_) => "Timeout",
122        E::TlsNotEnabled(_) => "TlsNotEnabled",
123        E::TlsProviderMissing => "TlsProviderMissing",
124        E::InvalidTlsConfig(_) => "InvalidTlsConfig",
125        _ => "Engine",
126    }
127}
128
129impl From<&Error> for ErrorPayload {
130    fn from(err: &Error) -> Self {
131        let kind = match err {
132            Error::SocketIo(e) => return ErrorPayload::from_core(e),
133            Error::UnknownClient(_) => "UnknownClient",
134            Error::AlreadyExists(_) => "AlreadyExists",
135            Error::AccessDenied(_) => "AccessDenied",
136            Error::UnknownAck(_) => "UnknownAck",
137            Error::Reserved(_) => "Reserved",
138            Error::UrlNotAllowed => "UrlNotAllowed",
139            Error::TooManySubscriptions(_) => "TooManySubscriptions",
140            Error::InvalidOptions(_) => "InvalidOptions",
141            Error::NotConfigurable(_) => "NotConfigurable",
142        };
143        ErrorPayload {
144            kind,
145            message: err.to_string(),
146            data: None,
147        }
148    }
149}
150
151impl Serialize for Error {
152    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
153        ErrorPayload::from(self).serialize(serializer)
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    /// Plugin errors here; socketio-next's (`ConnectRejected`, `HttpStatus`,
162    /// `WebsocketClosed`) come from real servers in the IPC tests.
163    #[test]
164    fn kinds_and_data() {
165        let denied = serde_json::to_value(Error::AccessDenied("core".into())).unwrap();
166        assert_eq!(denied["kind"], "AccessDenied");
167        assert!(denied.get("data").is_none());
168        let not =
169            serde_json::to_value(Error::SocketIo(socketio_next::Error::NotConnected)).unwrap();
170        assert_eq!(not["kind"], "NotConnected");
171    }
172}