Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
JoelTorresAr opened this issue Mar 26, 2023 · 0 comments

Comments

@JoelTorresAr
Copy link

JoelTorresAr commented Mar 26, 2023

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),
        })
    }
}```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant