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

Some or more documentation about custom error handlers. #48

Open DenuxPlays opened 9 months ago

DenuxPlays commented 9 months ago

I would love if there would be more documentation about error handlers available. The only thing I found was this comment

For example I went with this:

use actix_web_validator::error::flatten_errors;
use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;

#[derive(Serialize)]
pub struct ValidationErrorJsonPayload {
    pub message: String,
    pub fields: Vec<FieldError>,
}

#[derive(Serialize)]
pub struct FieldError {
    pub field_name: String,
    pub params: HashMap<String, Value>,
}

impl From<&validator::ValidationErrors> for ValidationErrorJsonPayload {
    fn from(error: &validator::ValidationErrors) -> Self {
        let errors = flatten_errors(error);
        let mut field_errors: Vec<FieldError> = Vec::new();
        for (index, field, error) in errors {
            field_errors.insert(
                index as usize,
                FieldError {
                    field_name: field,
                    params: error.params.clone().into_iter().map(|(key, value)| (key.into_owned(), value)).collect(),
                },
            )
        }
        ValidationErrorJsonPayload {
            message: "Validation error".to_owned(),
            fields: field_errors,
        }
    }
}

WIth this setup the actual error is getting returned