tauri_plugin_socketio/
error.rs1use serde::{Serialize, Serializer};
2use serde_json::{Value, json};
3use socketio_next::engineio;
4
5#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum Error {
10 #[error(transparent)]
12 SocketIo(#[from] socketio_next::Error),
13 #[error("no socket.io client with id `{0}`")]
15 UnknownClient(String),
16 #[error("a socket.io client with id `{0}` is registered already")]
18 AlreadyExists(String),
19 #[error("socket.io client `{0}` is read-only for the webview")]
22 AccessDenied(String),
23 #[error("no pending server ack {0} for this webview (answered, expired or unknown)")]
25 UnknownAck(u64),
26 #[error("the id `{0}` is reserved for a client registered from Rust")]
29 Reserved(String),
30 #[error("the server URL is not allowed by the socketio plugin configuration")]
32 UrlNotAllowed,
33 #[error("too many socket.io subscriptions for this webview (at most {0})")]
36 TooManySubscriptions(usize),
37 #[error("too many socket.io clients connected by this webview (at most {0})")]
40 TooManyClients(usize),
41 #[error("socket.io client `{0}` was registered from Rust: its connect values are Rust's")]
44 NotConfigurable(String),
45 #[error("invalid options: {0}")]
47 InvalidOptions(String),
48}
49
50pub type Result<T> = std::result::Result<T, Error>;
52
53#[derive(Debug, Clone, PartialEq, Serialize)]
59pub struct ErrorPayload {
60 pub kind: &'static str,
62 pub message: String,
64 #[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 #[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}