postal_code/
error.rs

1crate::ix!();
2
3/// Error type for postal code operations.
4#[derive(thiserror::Error,Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
5pub enum PostalCodeConstructionError {
6    /// The provided country is not supported by this library.
7    UnsupportedCountry {
8        /// Provided country that is not supported.
9        attempted_country: Country,
10    },
11    /// The provided postal code format is invalid for the specified country.
12    InvalidFormat {
13        /// Provided postal code that failed validation.
14        attempted_code: String,
15        /// Country code attempted.
16        attempted_country: Option<Country>,
17    },
18    /// Internal error: regex initialization failed.
19    RegexInitializationError {
20        /// The country whose regex failed initialization.
21        country: Country,
22    },
23}
24
25impl fmt::Display for PostalCodeConstructionError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            PostalCodeConstructionError::UnsupportedCountry { attempted_country } => {
29                write!(f, "Unsupported country: {}", attempted_country)
30            }
31            PostalCodeConstructionError::InvalidFormat { attempted_code, attempted_country } => {
32                match attempted_country {
33                    Some(country) => write!(
34                        f,
35                        "Invalid postal code format '{}' for country '{}'",
36                        attempted_code, country
37                    ),
38                    None => write!(
39                        f,
40                        "Invalid postal code format '{}', country unspecified",
41                        attempted_code
42                    ),
43                }
44            }
45            PostalCodeConstructionError::RegexInitializationError { country } => {
46                write!(f, "Regex initialization error for country '{}'", country)
47            }
48        }
49    }
50}
51
52impl From<derive_builder::UninitializedFieldError> for PostalCodeConstructionError {
53    fn from(_e: derive_builder::UninitializedFieldError) -> Self {
54        // Convert to a suitable error, for example:
55        PostalCodeConstructionError::InvalidFormat {
56            attempted_code: "<unset>".to_string(),
57            attempted_country: None,
58        }
59    }
60}