scsys_core/errors/
kinds.rs

1/*
2   Appellation: kinds <mod>
3   Contrib: FL03 <jo3mccain@icloud.com>
4*/
5#[cfg(feature = "alloc")]
6use alloc::string::String;
7use smart_default::SmartDefault;
8use strum::{AsRefStr, Display, EnumCount, EnumIs, VariantNames};
9
10pub trait ErrorTy {
11    fn name(&self) -> &str;
12}
13
14#[derive(
15    AsRefStr,
16    Clone,
17    Debug,
18    Display,
19    EnumCount,
20    EnumIs,
21    Eq,
22    Hash,
23    Ord,
24    PartialEq,
25    PartialOrd,
26    SmartDefault,
27    VariantNames,
28)]
29#[cfg_attr(
30    feature = "serde",
31    derive(serde::Deserialize, serde::Serialize),
32    serde(rename_all = "lowercase", untagged)
33)]
34#[non_exhaustive]
35#[strum(serialize_all = "lowercase")]
36pub enum Errors<T = String> {
37    Async,
38    Connection,
39    #[default]
40    Error(ExternalError<T>),
41    Execution,
42    IO,
43    Operation(OperationalError),
44    Parse,
45    Process,
46    Runtime,
47    Syntax,
48}
49
50impl<T> Errors<T> {
51    pub fn custom(error: T) -> Self {
52        Self::Error(ExternalError::custom(error))
53    }
54
55    pub fn unknown() -> Self {
56        Self::Error(ExternalError::Unknown)
57    }
58}
59
60macro_rules! err {
61    ($(#[$meta:meta])* $name:ident $($rest:tt)*) => {
62        #[derive(
63            Clone,
64            Copy,
65            Debug,
66            Eq,
67            Hash,
68            Ord,
69            PartialEq,
70            PartialOrd,
71            strum::AsRefStr,
72            strum::Display,
73            strum::EnumCount,
74            strum::EnumIs,
75            strum::VariantNames,
76        )]
77        #[cfg_attr(
78            feature = "serde",
79            derive(serde::Deserialize, serde::Serialize),
80            serde(rename_all = "lowercase", untagged)
81        )]
82        #[non_exhaustive]
83        #[strum(serialize_all = "lowercase")]
84        $(#[$meta])*
85        pub enum $name $($rest)*
86    };
87}
88
89macro_rules! impl_kind_from {
90    ($variant:ident, $kind:ident) => {
91        impl From<$kind> for Errors {
92            fn from(kind: $kind) -> Self {
93                Self::$variant(kind)
94            }
95        }
96    };
97    ($variant:ident, $($kind:ident),*) => {
98        $(
99            impl_kind_from!($variant, $kind);
100        )*
101    };
102}
103
104err! {
105    OperationalError {
106        Arithmetic,
107        System,
108    }
109}
110
111err! {
112    ExternalError<T = String> {
113        Custom(T),
114        Unknown,
115    }
116}
117
118impl<T> ExternalError<T> {
119    pub fn custom(error: T) -> Self {
120        Self::Custom(error)
121    }
122
123    pub fn unknown() -> Self {
124        Self::Unknown
125    }
126}
127
128impl<T> Default for ExternalError<T> {
129    fn default() -> Self {
130        Self::Unknown
131    }
132}
133
134impl_kind_from!(Error, ExternalError);
135impl_kind_from!(Operation, OperationalError);