1use std::process::ExitCode;
4use thiserror::Error;
5
6use crate::diagnostics;
7
8#[derive(Error, Debug)]
10pub enum CliError {
11 #[error("speaker \"{0}\" not found")]
12 SpeakerNotFound(String),
13
14 #[error("group \"{0}\" not found")]
15 GroupNotFound(String),
16
17 #[error("SDK error: {0}")]
18 Sdk(#[from] sonos_sdk::SdkError),
19
20 #[error("configuration error: {0}")]
21 Config(String),
22
23 #[error("validation error: {0}")]
24 Validation(String),
25}
26
27impl CliError {
28 pub fn recovery_hint(&self) -> Option<&'static str> {
30 match self {
31 Self::SpeakerNotFound(_) | Self::GroupNotFound(_) => {
32 Some(diagnostics::discovery_hint())
33 }
34 Self::Sdk(e) => {
35 if matches!(e, sonos_sdk::SdkError::DiscoveryFailed(_))
36 || e.to_string().contains("Network error")
37 {
38 Some(diagnostics::discovery_hint())
39 } else {
40 Some("Check network connectivity and speaker power.")
41 }
42 }
43 Self::Config(_) | Self::Validation(_) => None,
44 }
45 }
46
47 pub fn exit_code(&self) -> ExitCode {
49 match self {
50 Self::Validation(_) => ExitCode::from(2), _ => ExitCode::from(1), }
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn speaker_not_found_has_recovery_hint() {
62 let err = CliError::SpeakerNotFound("Kitchen".to_string());
63 assert!(err.recovery_hint().is_some());
64 assert!(err.recovery_hint().unwrap().contains("this could mean:"));
65 }
66
67 #[test]
68 fn group_not_found_has_recovery_hint() {
69 let err = CliError::GroupNotFound("Living Room".to_string());
70 assert!(err.recovery_hint().is_some());
71 }
72
73 #[test]
74 fn validation_error_has_no_hint() {
75 let err = CliError::Validation("invalid volume".to_string());
76 assert!(err.recovery_hint().is_none());
77 }
78
79 #[test]
80 fn validation_error_returns_exit_code_2() {
81 let err = CliError::Validation("bad input".to_string());
82 assert_eq!(err.exit_code(), ExitCode::from(2));
83 }
84
85 #[test]
86 fn runtime_errors_return_exit_code_1() {
87 let err = CliError::SpeakerNotFound("x".to_string());
88 assert_eq!(err.exit_code(), ExitCode::from(1));
89 }
90}