use std::fmt;
pub use wherr_macro::wherr;
#[cfg(feature = "anyhow")]
use anyhow::Error as AnyhowError;
#[cfg(feature = "anyhow")]
type Wherror = AnyhowError;
#[cfg(not(feature = "anyhow"))]
type Wherror = Box<dyn std::error::Error>;
pub struct Wherr {
pub inner: Wherror,
pub file: &'static str,
pub line: u32,
}
impl Wherr {
pub fn new(err: Wherror, file: &'static str, line: u32) -> Self {
Wherr {
inner: err,
file,
line,
}
}
}
impl fmt::Display for Wherr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}\nerror at {}:{}",
self.inner, self.file, self.line
)
}
}
impl fmt::Debug for Wherr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:?}\nerror at {}:{}",
self.inner, self.file, self.line
)
}
}
impl std::error::Error for Wherr {}
pub fn wherrapper<T, E>(
result: Result<T, E>,
file: &'static str,
line: u32,
) -> Result<T, Wherror>
where
E: Into<Wherror>,
{
match result {
Ok(val) => Ok(val),
Err(err) => {
let error: Wherror = err.into();
if error.is::<Wherr>() {
Err(error)
} else {
Err(Wherr::new(error, file, line).into())
}
}
}
}