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(_) => "Chrono parse error".to_owned(), GenericError::FromUTF8Error(_) => "UTF8 error".to_owned(), GenericError::IOError(e) => format!("IO error: {}", e), GenericError::MinreqError(_) => "Minreq error".to_owned(), GenericError::TomlError(_) => "Toml error".to_owned(), GenericError::YepzonServerError(_) => "Yepzon server error".to_owned(), 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()))), } } }