#[macro_export]
macro_rules! create_error {
( $error:ident => $( $error_reason:ident ),* ) => {
paste::paste! {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct $error {
pub reason: [<$error Reason>],
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(unused_qualifications)]
pub enum [<$error Reason>] {
$(
[<$error_reason>],
)*
}
impl $error {
$(
#[allow(unused_qualifications)]
pub fn [<$error_reason:snake>](message: String) -> $error {
$error {
reason: [<$error Reason>]::$error_reason,
message,
}
}
)*
$(
#[allow(unused_qualifications)]
pub fn [<map_to_ $error_reason:snake>]<E>(error: E) -> $error
where
E: std::error::Error,
{
let error_name = stringify!($error);
let error_reason_name = stringify!($error_reason);
let error_string =
format!("{}::{} caused by {}", error_name, error_reason_name, error);
$error {
reason: [<$error Reason>]::$error_reason,
message: error_string,
}
}
)*
}
impl std::error::Error for $error {}
impl std::fmt::Display for $error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let error_name = stringify!([<$error:camel>]);
write!(
f,
"{:#?} error, reason: {:#?}, message {:#?}",
error_name,
self.reason,
self.message
)
}
}
}
};
}