Skip to main content

timsrust_utils/
error.rs

1pub trait WrappedError:
2    std::fmt::Debug + std::fmt::Display + std::error::Error
3{
4}
5
6#[macro_export]
7macro_rules! simple_error {
8    (
9        $vis:vis
10        $err_ty:ident
11    ) => {
12        #[derive(Debug, Clone, PartialEq, Eq, Default)]
13        $vis struct $err_ty();
14
15        impl std::fmt::Display for $err_ty {
16            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17                write!(f, stringify!($err_ty))
18            }
19        }
20
21        impl std::error::Error for $err_ty {}
22
23        impl $crate::error::WrappedError for $err_ty {}
24    };
25}
26
27#[macro_export]
28macro_rules! custom_error {
29    (
30        $vis:vis
31        $err_ty:ident
32    ) => {
33        #[derive(Debug, Clone, PartialEq, Eq)]
34        $vis struct $err_ty(String);
35
36        impl $err_ty {
37            pub fn new(msg: impl Into<String>) -> Self {
38                Self(msg.into())
39            }
40        }
41
42        impl std::fmt::Display for $err_ty {
43            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44                write!(f, concat!(stringify!($err_ty), "({})"), self.0)
45            }
46        }
47
48        impl std::error::Error for $err_ty {}
49
50        impl $crate::error::WrappedError for $err_ty {}
51    };
52}
53
54#[macro_export]
55macro_rules! enumerated_error {
56    (
57        $vis:vis
58        $err_ty:ident,
59        $($variant:ident($from_ty:ty)),* $(,)?
60    ) => {
61        #[derive(Debug, Clone, PartialEq, Eq)]
62        $vis enum $err_ty {
63            $(
64                $variant($from_ty),
65            )*
66        }
67
68        impl std::fmt::Display for $err_ty {
69            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70                match self {
71                    $(
72                    Self::$variant(e) => write!(f, concat!(stringify!($err_ty), "({})"), e),
73                    )*
74                }
75            }
76        }
77
78        $(
79        impl From<$from_ty> for $err_ty where
80            $from_ty: $crate::error::WrappedError{
81            fn from(e: $from_ty) -> Self {
82                Self::$variant(e)
83            }
84        }
85        )*
86
87        impl std::error::Error for $err_ty {}
88
89        impl $crate::error::WrappedError for $err_ty {}
90    };
91}