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

Feature: Add Error with Extension in Validator #564

Conversation

cptrodgers
Copy link
Contributor

@cptrodgers cptrodgers commented Jul 8, 2021

Hi guys, this is my first contribution, please correct me.
My PR to help error data of input validator can contain more information by ErrorExtentionValues.

There are some use cases that I can imagine:

  • Use code number or code string for show exactly error (Bad Request, Internal Server Error) on Client Side.
  • Support localization (i18n) by adding key and its data on extensions.
  • ...

Example implementation:

    use async_graphql::*;
    pub struct IntGreaterThanZero;

    impl InputValueValidator for IntGreaterThanZero {
        fn is_valid_with_extensions(&self, value: &Value) -> Result<(), Error> {
            if let Value::Number(n) = value {
                if let Some(n) = n.as_i64() {
                    if n <= 0 {
                        let e = Error::new("Value must be greater than 0")
                            .extend_with(|_, e| e.set("code", 400));
                        return Err(e);
                    }
                }
            }
            Ok(())
        }
    }

Expected Output:

{
  "data": null,
  "errors": [
    {
      "message": "... Value must be greater than 0",
      "locations": [],
      "extensions": { "code": 400 }
    }
  ]
}

Compatible note:

  • Compatible with all logic code of fn is_valid.
  • Break MapErr logic on src/validators/mod.rs. Closure from fn(String) -> String to fn(Error) -> Error. Compatible.

@cptrodgers
Copy link
Contributor Author

cptrodgers commented Jul 8, 2021

cc @sunli829 . Feel free to correct me. Thanks.

@cptrodgers cptrodgers changed the title [WIP] Feature: Add Error with Extension in Validator Feature: Add Error with Extension in Validator Jul 8, 2021
@sunli829
Copy link
Collaborator

sunli829 commented Jul 9, 2021

Thank you very much, it looks great!
If you are free, please help update CHANGELOG. 🙂

@cptrodgers
Copy link
Contributor Author

cptrodgers commented Jul 9, 2021

Thank you very much, it looks great!
If you are free, please help update CHANGELOG. 🙂

Updated. Thanks @sunli829 .

@sunli829 sunli829 merged commit 5537d1d into async-graphql:master Jul 10, 2021
@cptrodgers cptrodgers deleted the feature/more-infor-when-output-validator branch July 10, 2021 02:13
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

Successfully merging this pull request may close these issues.

None yet

2 participants