Skip to main content

ec_validator/
error.rs

1use std::fmt;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
5#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
6pub enum ValidationError {
7    InvalidLength,
8    InvalidCheckDigit,
9    InvalidProvinceCode,
10    InvalidRucType,
11    InvalidFormat,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub struct ValidationErrorWithContext {
17    pub error: ValidationError,
18    pub context: Option<&'static str>,
19}
20
21impl ValidationError {
22    pub fn with_context(self, context: &'static str) -> ValidationErrorWithContext {
23        ValidationErrorWithContext {
24            error: self,
25            context: Some(context),
26        }
27    }
28}
29
30impl fmt::Display for ValidationError {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match self {
33            ValidationError::InvalidLength => write!(f, "invalid length"),
34            ValidationError::InvalidCheckDigit => write!(f, "invalid check digit"),
35            ValidationError::InvalidProvinceCode => write!(f, "invalid province code"),
36            ValidationError::InvalidRucType => write!(f, "invalid RUC type"),
37            ValidationError::InvalidFormat => write!(f, "invalid format"),
38        }
39    }
40}
41
42impl fmt::Display for ValidationErrorWithContext {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        if let Some(ctx) = self.context {
45            write!(f, "{}: {}", ctx, self.error)
46        } else {
47            write!(f, "{}", self.error)
48        }
49    }
50}
51
52impl std::error::Error for ValidationError {}
53impl std::error::Error for ValidationErrorWithContext {}