1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
   Appellation: error <mod>
   Contrib: FL03 <jo3mccain@icloud.com>
*/
use smart_default::SmartDefault;
use strum::{AsRefStr, EnumCount, EnumIs, EnumIter, VariantNames};

#[derive(
    AsRefStr,
    Clone,
    Debug,
    EnumCount,
    EnumIs,
    EnumIter,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    SmartDefault,
    VariantNames,
)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(rename_all = "lowercase", untagged)
)]
#[strum(serialize_all = "lowercase")]
pub enum ExternalError {
    Error(String),
    #[default]
    Unknown,
}

impl ExternalError {
    pub fn new(err: impl ToString) -> Self {
        let err = err.to_string();
        if err.is_empty() {
            return Self::unknown();
        }
        Self::error(err)
    }

    pub fn error(err: impl ToString) -> Self {
        ExternalError::Error(err.to_string())
    }

    pub fn unknown() -> Self {
        ExternalError::Unknown
    }
}

impl core::fmt::Display for ExternalError {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let msg = match self {
            ExternalError::Error(ref err) => err.to_string(),
            ExternalError::Unknown => "Unknown error".to_string(),
        };
        write!(f, "{}", msg)
    }
}

#[cfg(feature = "std")]
impl From<Box<dyn std::error::Error>> for ExternalError {
    fn from(err: Box<dyn std::error::Error>) -> Self {
        ExternalError::Error(err.to_string())
    }
}

error_from!(ExternalError::Error<&str, String>);