5

I would like to validate input provided by user during mutation and then provide errors if there are some invalid fields provided.

There is a question which answers the question for GraphQL-JS here

I want to ask this question about implementation using GraphQL-Java.

Let's say you have a form which posts data to API server. The API server validates the input and returns JSON object. If the input is invalid an error objects like the one below is returned.

{errors: {field1: "is required"}}

How do we handle and serve these kind of errors when using GraphQL? How and where should data validation be implemented (should that be part of GraphQL or should it be inside each resolve function)?

1 Answer 1

2

The graphql-java implementation has a class for checking if the query is not valid (i.e. graphql.validation.Validatior). That way you can validate your query string before executing them.

If the query is invalid you can create a method that takes List<ValidationError> as a parameter that generate the error response.

Example:

List<ValidationError> errors = validator.validateDocument(graphQLSchema, requestString);
if (!errors.isEmpty()) { return executeError(errors); }
Sign up to request clarification or add additional context in comments.

1 Comment

Just a note. Any valid GraphQL implementation, graphql-java included, will validate each query by itself, and an invalid query will never trigger execution. The question is only how customizable is the error-handling behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.