use super::api::ErrorModel; use std::fmt::{Display, Formatter}; use std::io; #[derive(Debug)] pub enum GenericError { TomlError(toml::de::Error), YepzonServerError(ErrorModel), MinreqError(minreq::Error), ChronoParseError(chrono::ParseError), IOError(io::Error), FromUTF8Error(std::string::FromUtf8Error), MessagedError(String, Box), } impl From for GenericError { fn from(error: toml::de::Error) -> Self { GenericError::TomlError(error) } } impl From for GenericError { fn from(error: minreq::Error) -> Self { GenericError::MinreqError(error) } } impl From for GenericError { fn from(error: chrono::ParseError) -> Self { GenericError::ChronoParseError(error) } } impl From for GenericError { fn from(error: ErrorModel) -> Self { GenericError::YepzonServerError(error) } } impl From for GenericError { fn from(error: io::Error) -> Self { GenericError::IOError(error) } } impl From for GenericError { fn from(error: std::string::FromUtf8Error) -> Self { GenericError::FromUTF8Error(error) } } impl Display for GenericError { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { let err = match self { GenericError::ChronoParseError(e) => format!("Date-Time value parse error: {}", e), GenericError::FromUTF8Error(e) => format!("UTF-8 error: {}", e), GenericError::IOError(e) => format!("IO error: {}", e), GenericError::MinreqError(e) => format!("Network error: {}", e), GenericError::TomlError(e) => format!("Toml error: {}", e), GenericError::YepzonServerError(e) => format!( "Yepzon server error: {}", e.message.as_ref().unwrap_or(&String::new()) ), GenericError::MessagedError(msg, err) => format!("{}\n {}", msg, err), }; write!(f, "{}", err) } } pub trait MessagedError { fn with_msg>(self, text: T) -> Result; } impl> MessagedError for Result { fn with_msg>(self, text: T) -> Result { match self { Ok(ok) => Ok(ok), Err(e) => Err(GenericError::MessagedError(text.into(), Box::new(e.into()))), } } }