Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling with graphql-java-tools and graphql-spring-boot-starter

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;
    }
}
like image 403
A.Sidor Avatar asked Aug 03 '26 14:08

A.Sidor


1 Answers

The GraphQL server returns an HTTP 200 when it can accept the request (the syntax is valid, the server is up...).

If an error occurs, it returns an 200 and fills the errors list in the response.

So, on client side, you will have:

  • Technical server errors, if the HTTP status is different from 200
  • Errors when handling the request (technical or not) if the HTTP status is 200 and the errors list is not empty
  • No error if the HTTP status is 200 and the errors list is not present (it should not be present and empty, according to the GraphQL spec)
like image 171
etienne-sf Avatar answered Aug 06 '26 21:08

etienne-sf