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