rambler-digital-solutions / actix-web-validator

Rust library for providing validation mechanism to actix-web with Validator crate.
MIT License
101 stars 26 forks source link

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

Open JoelTorresAr opened 1 year ago

JoelTorresAr commented 1 year ago

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<String> = 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),
        })
    }
}```