如何在 Spring 中为 GraphQL 实现异常处理程序

Paw*_*ski 4 java exception spring-mvc graphql graphql-java

我正在构建使用 GraphQL 和Leangen graphql-spqr 的Web 应用程序。
我有异常处理问题。例如,在服务类中,我使用 spring bean 验证来检查某些有效性,如果不正确,则抛出 ConstraintViolationException。
有没有办法添加一些异常处理程序来向客户端发送正确的消息?类似于ExceptionHandler用于 rest api 中的控制器?或者也许应该以其他方式完成?

Paw*_*ski 6

我发现的解决方案是实现 DataFetcherExceptionHandler,覆盖 onException 方法并将其设置为默认异常处理程序。

public class ExceptionHandler implements DataFetcherExceptionHandler {

    @Override
    public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) {

    Throwable exception = handlerParameters.getException();

    // do something with exception

    GraphQLError error = GraphqlErrorBuilder
            .newError()
            .message(exception.getMessage())
            .build();

    return DataFetcherExceptionHandlerResult
            .newResult()
            .error(error)
            .build();
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其设置为查询和突变的默认异常处理程序

GraphQL.newGraphQL(someSchema)
            .queryExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))
            .mutationExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))
            .build();
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您想保留默认值,则默认的突变策略是“AsyncSerialExecutionStrategy”。 (4认同)