Skip to main content

weirdnet_media/
error.rs

1//! The crate's error type.
2
3use std::fmt;
4
5/// What went wrong. Messages never contain the media itself, a transcript or a file's contents.
6#[derive(Debug)]
7#[non_exhaustive]
8pub enum MediaError {
9    /// The input can't be read as what it claims to be (a truncated WAV, an unknown container).
10    Invalid(String),
11    /// The input or the request is refused on purpose (a URL, a playlist, a disallowed format).
12    Refused(String),
13    /// A limit was reached (input size, output size, duration, a missing limit that planning needs).
14    Limit(String),
15    /// A child process ran past its time limit and was stopped.
16    Timeout {
17        /// The limit, in seconds.
18        seconds: u64,
19    },
20    /// ffmpeg or ffprobe is missing or couldn't start.
21    Unavailable(String),
22    /// ffmpeg or ffprobe exited with an error. `stderr` is truncated to 2 KiB.
23    Failed {
24        /// `ffmpeg` or `ffprobe`.
25        tool: &'static str,
26        /// The exit status, as text.
27        status: String,
28        /// The first 2 KiB of the child's stderr.
29        stderr: String,
30    },
31    /// An I/O error reading or writing a file the caller named.
32    Io(std::io::Error),
33}
34
35/// `Result` with [`MediaError`].
36pub type Result<T, E = MediaError> = std::result::Result<T, E>;
37
38impl MediaError {
39    pub(crate) fn invalid(msg: impl Into<String>) -> Self {
40        MediaError::Invalid(msg.into())
41    }
42
43    pub(crate) fn refused(msg: impl Into<String>) -> Self {
44        MediaError::Refused(msg.into())
45    }
46
47    pub(crate) fn limit(msg: impl Into<String>) -> Self {
48        MediaError::Limit(msg.into())
49    }
50}
51
52impl fmt::Display for MediaError {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            MediaError::Invalid(m) => write!(f, "invalid media: {m}"),
56            MediaError::Refused(m) => write!(f, "refused: {m}"),
57            MediaError::Limit(m) => write!(f, "limit: {m}"),
58            MediaError::Timeout { seconds } => write!(f, "stopped after the {seconds} s time limit"),
59            MediaError::Unavailable(m) => write!(f, "unavailable: {m}"),
60            MediaError::Failed { tool, status, stderr } => {
61                if stderr.is_empty() {
62                    write!(f, "{tool} failed ({status})")
63                } else {
64                    write!(f, "{tool} failed ({status}): {stderr}")
65                }
66            }
67            MediaError::Io(e) => write!(f, "i/o: {e}"),
68        }
69    }
70}
71
72impl std::error::Error for MediaError {
73    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
74        match self {
75            MediaError::Io(e) => Some(e),
76            _ => None,
77        }
78    }
79}
80
81impl From<std::io::Error> for MediaError {
82    fn from(e: std::io::Error) -> Self {
83        MediaError::Io(e)
84    }
85}