【问题标题】:How to implement exception handler for GraphQL in Spring如何在 Spring 中为 GraphQL 实现异常处理程序
【发布时间】:2020-01-07 11:31:48
【问题描述】:

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

【问题讨论】:

    标签: java spring-mvc exception graphql graphql-java


    【解决方案1】:

    我找到的解决方案是实现 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();
        }
    }
    

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

    GraphQL.newGraphQL(someSchema)
                .queryExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))
                .mutationExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))
                .build();
    

    【讨论】:

    • 请注意,如果您想保留默认值,突变的默认策略是AsyncSerialExecutionStrategy
    • 如果您想真正保留默认值,最好使用defaultDataFetcherExceptionHandler 方法设置异常处理程序。
    猜你喜欢
    • 1970-01-01
    • 2012-04-12
    • 2013-10-07
    • 2011-02-07
    • 2018-03-20
    • 2019-12-20
    • 2021-09-18
    • 1970-01-01
    • 2011-10-08
    相关资源
    最近更新 更多