Skip to main content

twilight_gateway/
error.rs

1//! Errors returned by gateway operations.
2
3#[cfg(any(feature = "zlib", feature = "zstd"))]
4pub use crate::compression::{CompressionError, CompressionErrorType};
5
6use std::{
7    error::Error,
8    fmt::{Debug, Display, Formatter, Result as FmtResult},
9};
10
11/// Sending a command over a channel failed.
12#[derive(Debug)]
13pub struct ChannelError {
14    /// Type of error.
15    pub(crate) kind: ChannelErrorType,
16    /// Source error if available.
17    pub(crate) source: Option<Box<dyn Error + Send + Sync>>,
18}
19
20impl ChannelError {
21    /// Immutable reference to the type of error that occurred.
22    #[must_use = "retrieving the type has no effect if left unused"]
23    pub const fn kind(&self) -> &ChannelErrorType {
24        &self.kind
25    }
26
27    /// Consume the error, returning the source error if there is any.
28    #[must_use = "consuming the error and retrieving the source has no effect if left unused"]
29    pub fn into_source(self) -> Option<Box<dyn Error + Send + Sync>> {
30        self.source
31    }
32
33    /// Consume the error, returning the owned error type and the source error.
34    #[must_use = "consuming the error into its parts has no effect if left unused"]
35    pub fn into_parts(self) -> (ChannelErrorType, Option<Box<dyn Error + Send + Sync>>) {
36        (self.kind, None)
37    }
38}
39
40impl Display for ChannelError {
41    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
42        match self.kind {
43            ChannelErrorType::Closed => f.write_str("tried sending over a closed channel"),
44        }
45    }
46}
47
48impl Error for ChannelError {
49    fn source(&self) -> Option<&(dyn Error + 'static)> {
50        self.source
51            .as_ref()
52            .map(|source| &**source as &(dyn Error + 'static))
53    }
54}
55
56/// Type of [`ChannelError`] that occurred.
57#[derive(Debug)]
58#[non_exhaustive]
59pub enum ChannelErrorType {
60    /// Tried sending over a closed channel.
61    Closed,
62}
63
64/// Receiving the next Websocket message failed.
65#[derive(Debug)]
66pub struct ReceiveMessageError {
67    /// Type of error.
68    pub(crate) kind: ReceiveMessageErrorType,
69    /// Source error if available.
70    pub(crate) source: Option<Box<dyn Error + Send + Sync>>,
71}
72
73impl ReceiveMessageError {
74    /// Immutable reference to the type of error that occurred.
75    #[must_use = "retrieving the type has no effect if left unused"]
76    pub const fn kind(&self) -> &ReceiveMessageErrorType {
77        &self.kind
78    }
79
80    /// Consume the error, returning the source error if there is any.
81    #[must_use = "consuming the error and retrieving the source has no effect if left unused"]
82    pub fn into_source(self) -> Option<Box<dyn Error + Send + Sync>> {
83        self.source
84    }
85
86    /// Consume the error, returning the owned error type and the source error.
87    #[must_use = "consuming the error into its parts has no effect if left unused"]
88    pub fn into_parts(
89        self,
90    ) -> (
91        ReceiveMessageErrorType,
92        Option<Box<dyn Error + Send + Sync>>,
93    ) {
94        (self.kind, None)
95    }
96
97    /// Shortcut to create a new error for a message compression error.
98    #[cfg(any(feature = "zlib", feature = "zstd"))]
99    pub(crate) fn from_compression(source: CompressionError) -> Self {
100        Self {
101            kind: ReceiveMessageErrorType::Compression,
102            source: Some(Box::new(source)),
103        }
104    }
105}
106
107impl Display for ReceiveMessageError {
108    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
109        match &self.kind {
110            #[cfg(any(feature = "zlib", feature = "zstd"))]
111            ReceiveMessageErrorType::Compression => {
112                f.write_str("binary message could not be decompressed")
113            }
114            ReceiveMessageErrorType::Deserializing { event } => {
115                f.write_str("gateway event could not be deserialized: event=")?;
116                f.write_str(event)
117            }
118            ReceiveMessageErrorType::Reconnect => f.write_str("failed to reconnect to the gateway"),
119        }
120    }
121}
122
123impl Error for ReceiveMessageError {
124    fn source(&self) -> Option<&(dyn Error + 'static)> {
125        self.source
126            .as_ref()
127            .map(|source| &**source as &(dyn Error + 'static))
128    }
129}
130
131/// Type of [`ReceiveMessageError`] that occurred.
132#[derive(Debug)]
133#[non_exhaustive]
134pub enum ReceiveMessageErrorType {
135    /// Binary message could not be decompressed.
136    ///
137    /// The associated error downcasts to [`CompressionError`].
138    #[cfg(any(feature = "zlib", feature = "zstd"))]
139    Compression,
140    /// Gateway event could not be deserialized.
141    Deserializing {
142        /// Gateway event.
143        ///
144        /// Note that the `simd-json` feature may slightly modify the event.
145        event: String,
146    },
147    /// Shard failed to reconnect to the gateway.
148    Reconnect,
149}
150
151#[cfg(test)]
152mod tests {
153    use super::{ReceiveMessageError, ReceiveMessageErrorType};
154    use static_assertions::assert_impl_all;
155    use std::{error::Error, fmt::Debug};
156
157    assert_impl_all!(ReceiveMessageErrorType: Debug, Send, Sync);
158    assert_impl_all!(ReceiveMessageError: Error, Send, Sync);
159
160    #[test]
161    fn receive_message_error_display() {
162        let messages: [(ReceiveMessageErrorType, &str); 3] = [
163            (
164                ReceiveMessageErrorType::Compression,
165                "binary message could not be decompressed",
166            ),
167            (
168                ReceiveMessageErrorType::Deserializing {
169                    event: r#"{"t":null,"s":null,"op":10,"d":{"heartbeat_interval":41250,"_trace":["[\"gateway-prd-us-east1-b-0568\",{\"micros\":0.0}]"]}}"#.to_owned(),
170                },
171                r#"gateway event could not be deserialized: event={"t":null,"s":null,"op":10,"d":{"heartbeat_interval":41250,"_trace":["[\"gateway-prd-us-east1-b-0568\",{\"micros\":0.0}]"]}}"#,
172            ),
173            (
174                ReceiveMessageErrorType::Reconnect,
175                "failed to reconnect to the gateway",
176            ),
177        ];
178
179        for (kind, message) in messages {
180            let error = ReceiveMessageError { kind, source: None };
181
182            assert_eq!(error.to_string(), message);
183        }
184    }
185}