concision_core/error/kinds/
external.rs

1/*
2   Appellation: error <mod>
3   Contrib: FL03 <jo3mccain@icloud.com>
4*/
5use smart_default::SmartDefault;
6use strum::{AsRefStr, EnumCount, EnumIs, EnumIter, VariantNames};
7
8#[derive(
9    AsRefStr,
10    Clone,
11    Debug,
12    EnumCount,
13    EnumIs,
14    EnumIter,
15    Eq,
16    Hash,
17    Ord,
18    PartialEq,
19    PartialOrd,
20    SmartDefault,
21    VariantNames,
22)]
23#[cfg_attr(
24    feature = "serde",
25    derive(serde::Deserialize, serde::Serialize),
26    serde(rename_all = "lowercase", untagged)
27)]
28#[strum(serialize_all = "lowercase")]
29pub enum ExternalError {
30    Error(String),
31    #[default]
32    Unknown,
33}
34
35impl ExternalError {
36    pub fn new(err: impl ToString) -> Self {
37        let err = err.to_string();
38        if err.is_empty() {
39            return Self::unknown();
40        }
41        Self::error(err)
42    }
43
44    pub fn error(err: impl ToString) -> Self {
45        ExternalError::Error(err.to_string())
46    }
47
48    pub fn unknown() -> Self {
49        ExternalError::Unknown
50    }
51}
52
53impl core::fmt::Display for ExternalError {
54    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
55        let msg = match self {
56            ExternalError::Error(ref err) => err.to_string(),
57            ExternalError::Unknown => "Unknown error".to_string(),
58        };
59        write!(f, "{}", msg)
60    }
61}
62
63#[cfg(feature = "std")]
64impl From<Box<dyn std::error::Error>> for ExternalError {
65    fn from(err: Box<dyn std::error::Error>) -> Self {
66        ExternalError::Error(err.to_string())
67    }
68}
69
70from_variant!(ExternalError::Error {<&str>.to_string(), <String>.to_string()});