#[derive(Debug, Clone, PartialEq)]
pub struct FieldError {
pub field: String,
pub message: String,
}
#[derive(Debug, Clone)]
pub struct ValidationErrors {
pub errors: Vec<FieldError>,
}
impl ValidationErrors {
pub fn message(msg: impl Into<String>) -> Self {
Self {
errors: vec![FieldError {
field: String::new(),
message: msg.into(),
}],
}
}
pub fn to_display(&self) -> String {
self.errors
.iter()
.map(|e| {
if e.field.is_empty() {
e.message.clone()
} else {
format!("{}: {}", e.field, e.message)
}
})
.collect::<Vec<_>>()
.join("; ")
}
}
impl std::fmt::Display for ValidationErrors {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_display())
}
}
impl std::error::Error for ValidationErrors {}
impl From<String> for ValidationErrors {
fn from(msg: String) -> Self {
Self::message(msg)
}
}
impl From<&str> for ValidationErrors {
fn from(msg: &str) -> Self {
Self::message(msg)
}
}