konduto/types/validation_errors.rs
1#[derive(Debug, Clone, PartialEq, thiserror::Error)]
2pub enum ValidationError {
3 #[error("Campo '{0}' não pode estar vazio")]
4 EmptyField(String),
5
6 #[error("Campo '{field}' excede o tamanho máximo de {max} caracteres (atual: {actual})")]
7 TooLong {
8 field: String,
9 max: usize,
10 actual: usize,
11 },
12
13 #[error("Campo '{field}' tem formato inválido: {message}")]
14 InvalidFormat { field: String, message: String },
15
16 #[error("Campo '{field}' fora do intervalo válido [{min}, {max}] (atual: {actual})")]
17 OutOfRange {
18 field: String,
19 min: f64,
20 max: f64,
21 actual: f64,
22 },
23
24 #[error("{0}")]
25 Generic(String),
26}
27
28/// Macro para implementar conversão automática de erros do nutype para ValidationError
29///
30/// Esta macro reduz o boilerplate de implementar `From<NutypeError> for ValidationError`
31/// para cada tipo validado usando nutype.
32///
33/// # Exemplo
34///
35/// ```rust
36/// use nutype::nutype;
37/// use konduto::impl_nutype_error_conversion;
38///
39/// #[nutype(
40/// sanitize(trim),
41/// validate(not_empty, len_char_max = 100),
42/// derive(Debug, Clone, Serialize, Deserialize)
43/// )]
44/// pub struct MyType(String);
45///
46/// // Antes: 5 linhas de código boilerplate
47/// // impl From<MyTypeError> for ValidationError {
48/// // fn from(err: MyTypeError) -> Self {
49/// // ValidationError::Generic(err.to_string())
50/// // }
51/// // }
52///
53/// // Depois: 1 linha
54/// impl_nutype_error_conversion!(MyTypeError);
55/// ```
56#[macro_export]
57macro_rules! impl_nutype_error_conversion {
58 ($error_type:ty) => {
59 impl From<$error_type> for $crate::types::validation_errors::ValidationError {
60 fn from(err: $error_type) -> Self {
61 $crate::types::validation_errors::ValidationError::Generic(err.to_string())
62 }
63 }
64 };
65}