I started to work with GraphQL for one week and I could not find out yet how to catch "internal" GraphQL errors like CoercingParseValueException. Because our Frontend use this endpoint to receive some information about shipping. When the schema or a required field is missing then GraphQL itself send an error which just got a message with arbitrary strings which you have to parse at the frontend to understand this message and show the client the correct error.
For our project, we defined a error-model for custom errors. This error-model contains a code field with a self defined code for every situtation like NotFoundException, ValidationException etc.
But how can I catch error from GraphQL and modify them?
Apporaches:
@Component
public class GraphQLErrorHandler implements graphql.servlet.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;
}
}
Does not work for me. ProcessErrors it is never called. I am using Spring Boot (Kickstarter Version)
For Custom errors I am using the new feature which was released for 10 days.
@Component("CLASSPATH TO THIS CLASS")
public class GraphQLExceptionHandler {
@ExceptionHandler({NotFoundException.class})
GraphQLError handleNotFoundException(NotFoundException e) {
return e;
}
@ExceptionHandler(ValidationException.class)
GraphQLError handleValidationException(ValidationException e) {
return e;
}
}
This approach works perfectly with custom error messages. To use this feature I have to enable the graphql-servlet property exception-handlers-enabled and set it to true. Nevertheless this approach does not catch "internal" Apollo/GraphQL errors even if the ExceptionHandler annotation is defined with Exception.class.
Maybe can help me with this problem?
Many thanks