How to handle errors in my graphQL API? I am using graphql-java-tools and graphql-spring-boot-starter. I created error handler but every time I get response 200 even when exception was thrown. Could you tell me how I should set error code e.g 400 in response?
@Component
public class CustomGraphQLErrorHandler implements GraphQLErrorHandler {
@Override
public List<GraphQLError> processErrors(List<GraphQLError> list) {
return list.stream().map(this::getNested).collect(Collectors.toList());
}
private GraphQLError getNested(GraphQLError error) {
if (error instanceof ExceptionWhileDataFetching) {
ExceptionWhileDataFetching exceptionError = (ExceptionWhileDataFetching) error;
if (exceptionError.getException() instanceof GraphQLError) {
return (GraphQLError) exceptionError.getException();
}
}
return error;
}
}
You can try to throw some exceptions in your error handling method e.g.
...except you'll only get the 400 status code and nothing more in your response because Spring is not here to handle the thrown exceptions as you're talking with the GraphQL servlet (not the Spring one) at e.g. http://127.0.0.1:8080/graphql
Only in your log you should be able to see the stacktrace: (this is just an example with a validation error for an unused fragment in the GraphQL query)
It's up to you to introduce a more complex handling of GraphQL errors, but that'll just be test & trial (as we've also done for quite some time...)