Skip to main content

djs_voice/
error.rs

1//! The errors of djs-voice: one type per operation (D-336).
2
3use core::fmt;
4use std::{error::Error, io};
5
6use crate::ogg::OggError;
7
8/// Why [`VoiceManager::join`](crate::VoiceManager::join) failed.
9///
10/// discord.js counterpart: none (`joinVoiceChannel` returns a `VoiceConnection` whose state
11/// becomes `Disconnected` or `Destroyed`); songbird: `JoinError`.
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum JoinError {
15    /// The [`VoiceGateway`](crate::VoiceGateway) could not send Opcode 4 (Update Voice
16    /// State) through the guild's shard; its error is the [`source`](Error::source).
17    Gateway(Box<dyn Error + Send + Sync>),
18    /// Discord did not answer, or the voice connection's handshake did not finish, within
19    /// 10 seconds (D-322). A bot without the Connect permission in the channel gets no
20    /// answer at all, so it sees this too.
21    Timeout,
22    /// The voice connection failed; why is the [`source`](Error::source).
23    Connection(Box<dyn Error + Send + Sync>),
24    /// The call was left, or joined to another channel, before this join finished.
25    Cancelled,
26}
27
28impl fmt::Display for JoinError {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        f.write_str(match self {
31            Self::Gateway(_) => "the voice state update could not be sent to the gateway",
32            Self::Timeout => "joining the voice channel timed out",
33            Self::Connection(_) => "the voice connection failed",
34            Self::Cancelled => "the join was cancelled by a leave or another join",
35        })
36    }
37}
38
39impl Error for JoinError {
40    fn source(&self) -> Option<&(dyn Error + 'static)> {
41        match self {
42            Self::Gateway(error) | Self::Connection(error) => Some(&**error),
43            Self::Timeout | Self::Cancelled => None,
44        }
45    }
46}
47
48/// Why an [`Input`](crate::Input) cannot be played.
49///
50/// discord.js counterpart: the errors of `createAudioResource` and prism-media's demuxers.
51#[derive(Debug)]
52#[non_exhaustive]
53pub enum InputError {
54    /// Reading the input failed.
55    Io(io::Error),
56    /// The input is not an Ogg stream: no Ogg page in its first 64 KiB.
57    NotOgg,
58    /// The Ogg stream does not hold Opus audio from its start, or its Opus headers are
59    /// malformed.
60    NotOpus,
61    /// [`Input::ffmpeg`](crate::Input::ffmpeg) found no `ffmpeg` program on `PATH`: FFmpeg
62    /// must be installed (<https://ffmpeg.org/download.html>) for it (D-362).
63    FfmpegMissing,
64    /// FFmpeg exited with an error: it could not read or decode the source (D-362).
65    #[non_exhaustive]
66    Ffmpeg {
67        /// Its exit code; `None` when it was ended by a signal.
68        code: Option<i32>,
69        /// The last lines of its standard error: why, as FFmpeg says it ("No such file or
70        /// directory", "Server returned 403 Forbidden", …).
71        message: String,
72    },
73}
74
75impl fmt::Display for InputError {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        match self {
78            Self::Io(error) => write!(f, "reading the input failed: {error}"),
79            Self::NotOgg => f.write_str("the input is not an Ogg stream"),
80            Self::NotOpus => f.write_str("the Ogg stream holds no well-formed Opus audio"),
81            Self::FfmpegMissing => f.write_str("ffmpeg is not installed (not found on PATH)"),
82            Self::Ffmpeg { code, message } => {
83                f.write_str("ffmpeg failed")?;
84                if let Some(code) = code {
85                    write!(f, " with exit code {code}")?;
86                }
87                if !message.is_empty() {
88                    write!(f, ": {message}")?;
89                }
90                Ok(())
91            }
92        }
93    }
94}
95
96impl Error for InputError {
97    fn source(&self) -> Option<&(dyn Error + 'static)> {
98        match self {
99            Self::Io(error) => Some(error),
100            Self::NotOgg | Self::NotOpus | Self::FfmpegMissing | Self::Ffmpeg { .. } => None,
101        }
102    }
103}
104
105impl From<io::Error> for InputError {
106    fn from(error: io::Error) -> Self {
107        Self::Io(error)
108    }
109}
110
111impl From<OggError> for InputError {
112    fn from(error: OggError) -> Self {
113        match error {
114            OggError::NotOgg => Self::NotOgg,
115            OggError::NotOpus | OggError::BadHead | OggError::BadTags => Self::NotOpus,
116        }
117    }
118}
119
120/// Why a [`TrackHandle`](crate::TrackHandle) control did nothing (D-339, D-360).
121///
122/// discord.js counterpart: none (`AudioPlayer#pause` returns `false`); songbird:
123/// `ControlError`.
124#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
125#[non_exhaustive]
126pub enum TrackError {
127    /// The track already ended: it played to its end, was stopped, replaced or skipped,
128    /// its input failed, or its call ended.
129    Ended,
130    /// The track cannot loop or seek: its input is a reader
131    /// ([`Input::ogg`](crate::Input::ogg), [`Input::pcm`](crate::Input::pcm)), which cannot
132    /// be opened again (D-360).
133    Unsupported,
134}
135
136impl fmt::Display for TrackError {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        f.write_str(match self {
139            Self::Ended => "the track has ended",
140            Self::Unsupported => "the track's input cannot be opened again to loop or seek",
141        })
142    }
143}
144
145impl Error for TrackError {}
146
147#[cfg(test)]
148mod tests {
149    use std::error::Error;
150
151    use super::{InputError, JoinError, TrackError};
152    use crate::ogg::OggError;
153
154    #[test]
155    fn errors_describe_themselves_and_their_causes() {
156        let cause: Box<dyn Error + Send + Sync> = "shard closed".into();
157        let error = JoinError::Gateway(cause);
158        assert_eq!(
159            error.to_string(),
160            "the voice state update could not be sent to the gateway"
161        );
162        assert_eq!(error.source().unwrap().to_string(), "shard closed");
163        assert!(JoinError::Timeout.source().is_none());
164        let io = InputError::from(std::io::Error::other("disk"));
165        assert_eq!(io.to_string(), "reading the input failed: disk");
166        assert!(io.source().is_some());
167        assert_eq!(TrackError::Ended.to_string(), "the track has ended");
168        assert_eq!(
169            InputError::Ffmpeg {
170                code: Some(1),
171                message: "a.mp3: No such file or directory".into()
172            }
173            .to_string(),
174            "ffmpeg failed with exit code 1: a.mp3: No such file or directory"
175        );
176        assert_eq!(
177            InputError::Ffmpeg {
178                code: None,
179                message: String::new()
180            }
181            .to_string(),
182            "ffmpeg failed"
183        );
184    }
185
186    #[test]
187    fn ogg_errors_become_input_errors() {
188        assert!(matches!(
189            InputError::from(OggError::NotOgg),
190            InputError::NotOgg
191        ));
192        for error in [OggError::NotOpus, OggError::BadHead, OggError::BadTags] {
193            assert!(matches!(InputError::from(error), InputError::NotOpus));
194        }
195    }
196}