/// Errors the app can act on. Messages are for logs, not for display. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Error { /// Wrong username or password, or the server refuses token sign-in. #[error("unauthorized: {0}")] Unauthorized(String), /// The address isn't a usable http(s) URL. #[error("invalid server address: {0}")] InvalidUrl(String), /// The album, artist or playlist doesn't exist (any more). #[error("not found: {0}")] NotFound(String), /// No connection, DNS failure, timeout: worth retrying. #[error("network: {0}")] Network(String), /// Anything else the server rejected, or a reply that isn't Subsonic. #[error("api: {0}")] Api(String), } pub type Result = std::result::Result; impl Error { /// Subsonic error codes: 40 wrong credentials, 41 token auth unsupported /// (LDAP users), 70 not found. pub(crate) fn from_code(code: i64, message: String) -> Self { match code { 40 | 41 => Error::Unauthorized(message), 70 => Error::NotFound(message), _ => Error::Api(format!("{code}: {message}")), } } } impl From for Error { fn from(e: reqwest::Error) -> Self { if e.is_decode() { Error::Api(e.to_string()) } else if e.status() == Some(reqwest::StatusCode::UNAUTHORIZED) { Error::Unauthorized(e.to_string()) } else if e.status() == Some(reqwest::StatusCode::NOT_FOUND) { // Usually a wrong address: the host answers, but has no /rest. Error::Api(e.to_string()) } else { Error::Network(e.to_string()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn subsonic_codes_map_to_actionable_errors() { assert!(matches!(Error::from_code(40, "Wrong username or password".into()), Error::Unauthorized(_))); assert!(matches!(Error::from_code(41, String::new()), Error::Unauthorized(_))); assert!(matches!(Error::from_code(70, "Album not found".into()), Error::NotFound(_))); assert_eq!(Error::from_code(0, "boom".into()), Error::Api("0: boom".into())); } }