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("socket.io client `{0}` was registered from Rust: its connect values are Rust's")]
40 NotConfigurable(String),
41 #[error("invalid options: {0}")]
43 InvalidOptions(String),
44}
45
46pub type Result<T> = std::result::Result<T, Error>;
48
49#[derive(Debug, Clone, PartialEq, Serialize)]
55pub struct ErrorPayload {
56 pub kind: &'static str,
58 pub message: String,
60 #[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 #[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}