GraphQL java - using SourceLocations to extract the field from a ValidationError

451 Views Asked by At

Supposing I have a simple GraphQL schema:

type Query {
  test(requestId: String!): String
}

and I execute a query like this (intentionally passing a Number instead of a String as 'requestId' value):

query {
 test(requestId: 5)
}

Then I have a Java snippet where I execute the query manually:

// code

ExecutionInput executionInput = ExecutionInput.newExecutionInput()
  .query(query)
  .variables(variables)
  .build();

ExecutionResult executionResult = graphQL.execute(executionInput);

if (!executionResult.getErrors().isEmpty()) {
  GraphQLError error = executionResult.getErrors().get(0);

  if (error instanceof ValidationError validationError) {
    // Extract the field in error here (maybe with SourceLocations from "validationError" obj)
  }
}

// code

I expect to get a ValidationError, and I get it but this is his content:

ValidationError{validationErrorType=WrongType, queryPath=[test], message=Validation error of type WrongType: argument 'requestId' with value 'IntValue{value=5}' is not a valid 'String' @ 'test', locations=[SourceLocation{line=2, column=8}], description='argument 'requestId' with value 'IntValue{value=5}' is not a valid 'String''}

the content of validationError.getSourceLocations().get(0).getSourceName() is null!


Is possible to get the name of the field who has not passed the validation (in this case requestId)?

I'm able to create a Document object doing something like this:

Document document = new Parser().parseDocument(query);

Maybe is possible to interpolate SourceLocations with the Document in order to retrieve the "failed field".

I tried a lot of stuff but without luck, maybe someone has faced the same before.

0

There are 0 best solutions below