use std::{
backtrace::{Backtrace, BacktraceStatus},
fmt::{self, Display, Formatter},
};
#[macro_export]
macro_rules! err {
(with: $error:expr, $($arg:tt)*) => {{
let error = format!($($arg)*);
let source = Box::new($error);
$crate::error::Error::new(error, Some(source))
}};
($($arg:tt)*) => {{
let error = format!($($arg)*);
$crate::error::Error::new(error, None)
}};
}
#[derive(Debug)]
pub struct Error {
pub error: String,
pub source: Option<Box<dyn std::error::Error + Send>>,
pub backtrace: Backtrace,
}
impl Error {
pub fn new(error: String, source: Option<Box<dyn std::error::Error + Send>>) -> Self {
let backtrace = Backtrace::capture();
Self { error, source, backtrace }
}
pub fn has_backtrace(&self) -> bool {
self.backtrace.status() == BacktraceStatus::Captured
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
writeln!(f, "{}", self.error)?;
if let Some(source) = &self.source {
writeln!(f, " caused by: {source}")?;
}
Ok(())
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
#[allow(clippy::borrowed_box, reason = "Type gymnastics to remove the `Send`")]
let source: &Box<dyn std::error::Error + Send> = self.source.as_ref()?;
let source: &dyn std::error::Error = source.as_ref();
Some(source)
}
}