yepzon-locationer/src/errors.rs

52 lines
1.5 KiB
Rust
Raw Normal View History

2020-08-24 01:17:50 +02:00
use std::fmt::{Display, Formatter};
2020-08-23 02:08:05 +02:00
#[derive(Debug)]
pub enum GenericError {
2020-08-29 01:27:23 +02:00
ThingyLibError(thingy_lib::Error),
2020-08-24 22:24:26 +02:00
GPXError(gpx::errors::Error),
2020-08-24 18:50:29 +02:00
MessagedError(String, Option<Box<GenericError>>),
2020-08-23 02:08:05 +02:00
}
2020-08-29 01:27:23 +02:00
impl From<thingy_lib::Error> for GenericError {
fn from(error: thingy_lib::Error) -> Self {
GenericError::ThingyLibError(error)
2020-08-23 19:54:34 +02:00
}
}
2020-08-24 01:17:50 +02:00
2020-08-24 22:24:26 +02:00
impl From<gpx::errors::Error> for GenericError {
fn from(error: gpx::errors::Error) -> Self {
GenericError::GPXError(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-29 01:27:23 +02:00
GenericError::ThingyLibError(e) => e.to_string(),
GenericError::GPXError(e) => format!("GPX error: {}", e),
2020-08-24 18:50:29 +02:00
GenericError::MessagedError(msg, err) => format!(
"{}\n {}",
msg,
err.as_ref().map(|e| e.to_string()).unwrap_or(String::new())
),
2020-08-24 01:17:50 +02:00
};
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),
2020-08-24 18:50:29 +02:00
Err(e) => Err(GenericError::MessagedError(
text.into(),
Some(Box::new(e.into())),
)),
2020-08-24 01:17:50 +02:00
}
}
}