use std::{
backtrace::Backtrace,
fmt::{self, Display, Formatter},
};
#[macro_export]
macro_rules! error {
($kind:expr, with: $error:expr) => {{
let error = $error.to_string();
let source = Box::new($error);
$crate::error::Error::new($kind, error, Some(source))
}};
($kind:expr, with: $error:expr, $($arg:tt)*) => {{
let error = format!($($arg)*);
let source = Box::new($error);
$crate::error::Error::new($kind, error, Some(source))
}};
($kind:expr, $($arg:tt)*) => {{
let error = format!($($arg)*);
$crate::error::Error::new($kind, error, None)
}};
}
#[derive(Debug)]
pub enum ErrorKind {
PathError,
ExecError,
ChildError,
}
impl Display for ErrorKind {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::PathError => write!(f, "Failed to find the requested binary"),
Self::ExecError => write!(f, "Failed to execute the child"),
Self::ChildError => write!(f, "The child exited with a non-zero error code"),
}
}
}
#[derive(Debug)]
pub struct Error {
pub kind: ErrorKind,
pub message: String,
pub source: Option<Box<dyn std::error::Error + Send>>,
pub backtrace: Backtrace,
}
impl Error {
#[doc(hidden)]
pub fn new(kind: ErrorKind, message: String, source: Option<Box<dyn std::error::Error + Send>>) -> Self {
let backtrace = Backtrace::capture();
Self { kind, message, source, backtrace }
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
writeln!(f, "{}: {}", self.kind, self.message)?;
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)> {
let source = self.source.as_ref()?;
Some(source.as_ref())
}
}