/// Errors the app can act on. Messages are for logs, not for display. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Error { /// The token is missing, revoked or expired. Sign in again. #[error("unauthorized: {0}")] Unauthorized(String), /// The sign-in code ran out before the user confirmed it. #[error("sign-in code expired")] CodeExpired, /// The user declined access on Yandex's page. #[error("sign-in was declined")] Denied, /// No connection, DNS failure, timeout: worth retrying. #[error("network: {0}")] Network(String), /// Anything else the server or the decoder rejected. #[error("api: {0}")] Api(String), } pub type Result = std::result::Result; impl Error { pub fn is_retryable(&self) -> bool { matches!(self, Error::Network(_)) } } impl From for Error { fn from(e: yamuse::Error) -> Self { use yamuse::Error as Y; match e { Y::Unauthorized(m) => Error::Unauthorized(m), Y::Network(m) => Error::Network(m), Y::TimedOut => Error::Network("timed out".into()), Y::RateLimited { message, .. } => Error::Network(message), Y::DeviceAuth(m) => classify_oauth(&m), other => Error::Api(other.to_string()), } } } /// OAuth rejections arrive as free text carrying the RFC 8628 error code. fn classify_oauth(message: &str) -> Error { let m = message.to_ascii_lowercase(); if m.contains("expired") || m.contains("timed out") { Error::CodeExpired } else if m.contains("denied") { Error::Denied } else if m.contains("invalid_grant") || m.contains("bad refresh") { Error::Unauthorized(message.to_owned()) } else { Error::Api(message.to_owned()) } } #[cfg(test)] mod tests { use super::*; #[test] fn oauth_codes_map_to_actionable_errors() { assert_eq!(classify_oauth("expired_token: code expired"), Error::CodeExpired); assert_eq!(classify_oauth("device authorization timed out"), Error::CodeExpired); assert_eq!(classify_oauth("access_denied"), Error::Denied); assert!(matches!(classify_oauth("invalid_grant"), Error::Unauthorized(_))); assert!(matches!(classify_oauth("something new"), Error::Api(_))); } #[test] fn only_network_errors_retry() { assert!(Error::Network("dns".into()).is_retryable()); assert!(!Error::Unauthorized(String::new()).is_retryable()); assert!(!Error::CodeExpired.is_retryable()); } }