yepzon-locationer/src/errors.rs

82 lines
2.4 KiB
Rust
Raw Normal View History

2020-08-23 02:08:05 +02:00
use super::api::ErrorModel;
2020-08-24 01:17:50 +02:00
use std::fmt::{Display, Formatter};
2020-08-23 02:08:05 +02:00
use std::io;
#[derive(Debug)]
pub enum GenericError {
TomlError(toml::de::Error),
YepzonServerError(ErrorModel),
MinreqError(minreq::Error),
ChronoParseError(chrono::ParseError),
IOError(io::Error),
2020-08-23 19:54:34 +02:00
FromUTF8Error(std::string::FromUtf8Error),
2020-08-24 01:17:50 +02:00
MessagedError(String, Box<GenericError>),
2020-08-23 02:08:05 +02:00
}
impl From<toml::de::Error> for GenericError {
fn from(error: toml::de::Error) -> Self {
GenericError::TomlError(error)
}
}
impl From<minreq::Error> for GenericError {
fn from(error: minreq::Error) -> Self {
GenericError::MinreqError(error)
}
}
impl From<chrono::ParseError> for GenericError {
fn from(error: chrono::ParseError) -> Self {
GenericError::ChronoParseError(error)
}
}
impl From<ErrorModel> for GenericError {
fn from(error: ErrorModel) -> Self {
GenericError::YepzonServerError(error)
}
}
impl From<io::Error> for GenericError {
fn from(error: io::Error) -> Self {
GenericError::IOError(error)
}
}
2020-08-23 19:54:34 +02:00
impl From<std::string::FromUtf8Error> for GenericError {
fn from(error: std::string::FromUtf8Error) -> Self {
GenericError::FromUTF8Error(error)
}
}
2020-08-24 01:17:50 +02:00
impl Display for GenericError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
let err = match self {
2020-08-24 02:33:40 +02:00
GenericError::ChronoParseError(e) => format!("Date-Time value parse error: {}", e),
GenericError::FromUTF8Error(e) => format!("UTF-8 error: {}", e),
2020-08-24 01:17:50 +02:00
GenericError::IOError(e) => format!("IO error: {}", e),
2020-08-24 02:33:40 +02:00
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())
),
2020-08-24 01:17:50 +02:00
GenericError::MessagedError(msg, err) => format!("{}\n {}", msg, err),
};
write!(f, "{}", err)
}
}
pub trait MessagedError<A> {
fn with_msg<T: Into<String>>(self, text: T) -> Result<A, GenericError>;
}
impl<A, B: Into<GenericError>> MessagedError<A> for Result<A, B> {
fn with_msg<T: Into<String>>(self, text: T) -> Result<A, GenericError> {
match self {
Ok(ok) => Ok(ok),
Err(e) => Err(GenericError::MessagedError(text.into(), Box::new(e.into()))),
}
}
}