【问题标题】:GraphQL - How to catch "Internal" Apollo/GraphQL errors - Java Spring BootGraphQL - 如何捕获“内部”Apollo/GraphQL 错误 - Java Spring Boot
【发布时间】:2019-05-15 10:23:52
【问题描述】:

我开始使用 GraphQL 一周,但我还不知道如何捕获像 CoercingParseValueException 这样的“内部”GraphQL 错误。因为我们的前端使用这个端点来接收一些关于运输的信息。当模式或必填字段丢失时,GraphQL 本身会发送一个错误,该错误只会收到一条带有任意字符串的消息,您必须在前端解析该消息才能理解此消息并向客户端显示正确的错误。

对于我们的项目,我们为自定义错误定义了一个错误模型。此错误模型包含一个代码字段,其中包含针对 NotFoundException、ValidationException 等每种情况的自定义代码。

但是我怎样才能从 GraphQL 中捕获错误并修改它们呢?

方法:

@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;
    }

} 

对我不起作用。 ProcessErrors 它永远不会被调用。我正在使用 Spring Boot (Kickstarter Version)

对于自定义错误,我正在使用发布了 10 天的新功能。

@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;
    }
}

这种方法与自定义错误消息完美配合。要使用此功能,我必须启用 graphql-servlet 属性 exception-handlers-enabled 并将其设置为 true。然而,即使 ExceptionHandler 注释是用 Exception.class 定义的,这种方法也不会捕获“内部”Apollo/GraphQL 错误。

也许可以帮助我解决这个问题?

非常感谢

【问题讨论】:

    标签: java spring spring-boot graphql apollo


    【解决方案1】:

    试试这个。您应该为一般异常返回 ThrowableGraphQLError 类型

    @ExceptionHandler(Exception::class)
    fun handleException(e: Exception): ThrowableGraphQLError {
        log.error("{}", e)
        return ThrowableGraphQLError(e, "Internal Server Error")
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-15
      • 2018-07-30
      • 2021-09-09
      • 2020-09-16
      • 1970-01-01
      • 2020-04-20
      • 2020-05-16
      • 2017-06-23
      • 2018-12-27
      相关资源
      最近更新 更多