Skip to main content

radio_cli/
error.rs

1use std::{collections::BTreeMap, fmt};
2
3// Variants and their stable public codes are defined below.
4macro_rules! codes {
5    ($($variant:ident => ($code:literal, $exit:literal)),+ $(,)?) => {
6        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
7        pub enum ErrorCode { $($variant),+ }
8        impl ErrorCode {
9            pub const ALL: &'static [Self] = &[$(Self::$variant),+];
10            pub fn exit_code(self) -> i32 { match self { $(Self::$variant => $exit),+ } }
11            pub fn as_str(self) -> &'static str { match self { $(Self::$variant => $code),+ } }
12        }
13    }
14}
15
16codes! {
17    UsageError => ("usage_error", 2),
18    InvalidUrl => ("invalid_url", 1),
19    MediaBusy => ("media_busy", 4),
20    StationNotFound => ("station_not_found", 1),
21    InvalidStation => ("invalid_station", 1),
22    InvalidUuid => ("invalid_uuid", 2),
23    DatabaseTooNew => ("database_too_new", 1),
24    Cancelled => ("cancelled", 1),
25    EmptyCatalog => ("empty_catalog", 1),
26    NoDirectoryServers => ("no_directory_servers", 1),
27    DirectoryRequest => ("directory_request", 1),
28    DirectoryResponseTooLarge => ("directory_response_too_large", 1),
29    InvalidPagination => ("invalid_pagination", 1),
30    CatalogTooLarge => ("catalog_too_large", 1),
31    CatalogShrink => ("catalog_shrink", 1),
32    DirectorySync => ("directory_sync", 1),
33    DataDirectory => ("data_directory", 1),
34    InvalidConfig => ("invalid_config", 1),
35    ReadConfig => ("read_config", 1),
36    InvalidSettings => ("invalid_settings", 1),
37    UnsupportedCodec => ("unsupported_codec", 1),
38    FinalPathMissing => ("final_path_missing", 1),
39    RecordingPublish => ("recording_publish", 1),
40    RecordingSizeMismatch => ("recording_size_mismatch", 1),
41    NoAudio => ("no_audio", 1),
42    MissingDependency => ("missing_dependency", 3),
43    InvalidDuration => ("invalid_duration", 2),
44    DurationUnit => ("duration_unit", 2),
45    DurationOverflow => ("duration_overflow", 2),
46    DurationRange => ("duration_range", 2),
47    NoStream => ("no_stream", 1),
48    RandomDisabled => ("random_disabled", 1),
49    NoMatchingStation => ("no_matching_station", 1),
50    NotPlaying => ("not_playing", 1),
51    WaitForPlayback => ("wait_for_playback", 1),
52    RecordingBusy => ("recording_busy", 1),
53    NoRecordingStream => ("no_recording_stream", 1),
54    RecordingSourcesFailed => ("recording_sources_failed", 1),
55    RuntimePathTooLong => ("runtime_path_too_long", 1),
56    PlayerStartup => ("player_startup", 1),
57    AudioDeviceFailed => ("audio_device_failed", 1),
58    AudioDevicesUnavailable => ("audio_devices_unavailable", 1),
59    NormalizationUnavailable => ("normalization_unavailable", 1),
60    PlayerClosed => ("player_closed", 1),
61    PlayerMessageTooLarge => ("player_message_too_large", 1),
62    PlayerExited => ("player_exited", 1),
63    ProcessTimeout => ("process_timeout", 1),
64    ArtworkHandoffTimeout => ("artwork_handoff_timeout", 1),
65    ProcessFailed => ("process_failed", 1),
66    BackgroundFailed => ("background_failed", 1),
67    EmptyStationName => ("empty_station_name", 2),
68    DuplicateStation => ("duplicate_station", 1),
69    NotCustom => ("not_custom", 1),
70    RecordingNotFound => ("recording_not_found", 1),
71    RecordingInUse => ("recording_in_use", 1),
72    InsufficientSpace => ("insufficient_space", 1),
73    LocalRecording => ("local_recording", 1),
74    EphemeralRecording => ("ephemeral_recording", 1),
75}
76
77#[derive(Debug, Clone)]
78pub struct DomainError {
79    pub code: ErrorCode,
80    pub params: BTreeMap<String, String>,
81}
82
83impl DomainError {
84    pub fn new(code: ErrorCode) -> Self {
85        Self {
86            code,
87            params: BTreeMap::new(),
88        }
89    }
90    pub fn with(mut self, key: &str, value: impl ToString) -> Self {
91        self.params.insert(key.into(), value.to_string());
92        self
93    }
94}
95impl fmt::Display for DomainError {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        let template = crate::messages::text(self.code.as_str());
98        // Substitute once so user-provided values cannot become placeholders.
99        let mut rest = template;
100        while let Some(start) = rest.find('{') {
101            f.write_str(&rest[..start])?;
102            let Some(end) = rest[start..].find('}') else {
103                return f.write_str(&rest[start..]);
104            };
105            let key = &rest[start + 1..start + end];
106            if let Some(value) = self.params.get(key) {
107                f.write_str(value)?;
108            } else {
109                write!(f, "{{{key}}}")?;
110            }
111            rest = &rest[start + end + 1..];
112        }
113        f.write_str(rest)
114    }
115}
116impl std::error::Error for DomainError {}
117
118pub fn exit_code(error: &anyhow::Error) -> i32 {
119    error
120        .downcast_ref::<DomainError>()
121        .map_or(1, |e| e.code.exit_code())
122}
123
124pub fn json_error(error: &anyhow::Error) -> serde_json::Value {
125    let domain = error.downcast_ref::<DomainError>();
126    serde_json::json!({"ok":false,"error":{
127        "code":domain.map(|e| e.code.as_str()).unwrap_or("general_error"),
128        "message":crate::clean_text(&format!("{error:#}")),
129        "params":domain.map(|e| e.params.clone()).unwrap_or_default()
130    }})
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    #[test]
137    fn domain_exit_classes_are_explicit() {
138        for (code, expected) in [
139            (ErrorCode::UsageError, 2),
140            (ErrorCode::InvalidDuration, 2),
141            (ErrorCode::DurationRange, 2),
142            (ErrorCode::MissingDependency, 3),
143            (ErrorCode::MediaBusy, 4),
144            (ErrorCode::InvalidSettings, 1),
145            (ErrorCode::StationNotFound, 1),
146        ] {
147            assert_eq!(exit_code(&DomainError::new(code).into()), expected);
148        }
149        assert_eq!(exit_code(&anyhow::anyhow!("I/O")), 1);
150    }
151
152    #[test]
153    fn runtime_path_too_long_reports_the_offending_path() {
154        let error = DomainError::new(ErrorCode::RuntimePathTooLong)
155            .with("path", "/deep/dir/run/mpv-abc.sock");
156        assert!(error.to_string().contains("/deep/dir/run/mpv-abc.sock"));
157    }
158}