rambler-digital-solutions / actix-web-validator

Rust library for providing validation mechanism to actix-web with Validator crate.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return validation error in a format that can be processed on the frontend

JoelTorresAr opened this issue · comments

The error response it gives could be improved, I have the following suggestion:

impl ResponseError for Error {
fn error_response(&self) -> HttpResponse {
HttpResponse::build(StatusCode::UNPROCESSABLE_ENTITY).body(match self {
Self::Validate(e) => {
println!("Validation errors: {:#?}", e);
//convert into ErrorResponse
let mut errors = HashMap::new();
for (field, val_errors) in e.clone().field_errors() {
let mut error_messages: Vec = Vec::new();
for err in val_errors {
if err.message.is_some() {
error_messages.push(err.message.clone().unwrap().to_string());
continue;
}else {
error_messages.push(err.code.to_string());
}
}
errors.insert(field.to_string(), error_messages);
}
let error_response = ErrorResponse{
message: "Validation error".to_string(),
errors
};
serde_json::to_string(&error_response).unwrap()
}
_ => format!("{}", *self),
})
}
}