use std::fmt;
pub use wherr_macro::wherr;
pub struct Wherr {
pub inner: Box<dyn std::error::Error>,
pub file: &'static str,
pub line: u32,
}
impl Wherr {
pub fn new(err: Box<dyn std::error::Error>, 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, Box<dyn std::error::Error>>
where
E: Into<Box<dyn std::error::Error>>,
{
match result {
Ok(val) => Ok(val),
Err(err) => {
let boxed_err: Box<dyn std::error::Error> = err.into();
if boxed_err.is::<Wherr>() {
Err(boxed_err)
} else {
Err(Box::new(Wherr::new(boxed_err, file, line)))
}
}
}
}