使用 graphql-java-tools 和 graphql-spring-boot-starter 进行错误处理

A.S*_*dor 6 java spring graphql graphql-java-tools

如何处理 graphQL API 中的错误?我正在使用 graphql-java-tools 和 graphql-spring-boot-starter。我创建了错误处理程序,但每次我都会收到响应 200,即使抛出异常也是如此。你能告诉我应该如何设置错误代码(例如 400)作为响应吗?

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

eti*_*-sf 5

当 GraphQL 服务器可以接受请求时,它会返回 HTTP 200(语法有效,服务器已启动...)。

如果发生错误,它将返回 200 并填充响应中的错误列表。

因此,在客户端,您将拥有:

  • 如果 HTTP 状态不同于 200,则表示服务器技术错误
  • 如果 HTTP 状态为 200 并且错误列表不为空,则处理请求时出现错误(技术性或非技术性)
  • 如果 HTTP 状态为 200 并且错误列表不存在,则不会出现错误(根据 GraphQL 规范,错误列表不应存在且为空)