在GraphQL-SPQR中返回错误的正确方法

时间:2019-07-26 07:40:25

标签: java spring-boot validation graphql graphql-spqr

此刻,我抛出RuntimeException来返回GraphQL验证错误。它工作异常出色,但它会在我的日志中引发带有大堆栈跟踪的可怕错误。

在这里您可以看到我正在检查提交的新用户注册突变,以确保密码彼此匹配并且电子邮件地址尚未使用。

在GraphQL SPQR Spring Boot Starter中执行此操作的正确方法是什么。

@GraphQLMutation (name="register")
public User register(@GraphQLArgument(name="firstname") String firstname, @GraphQLArgument(name="lastname") String lastname, @GraphQLArgument(name="email") String email, @GraphQLArgument(name="msisdn") String msisdn, @GraphQLArgument(name="password") String password, @GraphQLArgument (name="confirmPassword") String confirmPassword) {
    if (userRepo.findByEmail(email) != null) {
        throw new RuntimeException("User already exists");
    }

    if (!password.equals(confirmPassword)) {
        throw new RuntimeException("Passwords do not match");
    }

    User newUser = new User();
    //...
    return userRepo.save(newUser);
}

1 个答案:

答案 0 :(得分:3)

我不清楚您在问什么...但是我假设您想自定义正在记录的内容。

对于初学者来说,我建议使用List(((0, 1, 2, 3), (1, 1, 2, 7), (4, 1, 2, 8)), ((3, 1, 3, 7),(6, 1, 3, 5)),((5, 1, 5, 4), (2, 1, 5, 5))) 之类的专用异常类型,您可以以不同的方式捕获和处理该异常。

对于日志记录,它可能发生在grapqh-java中,因为SPQR本身不会记录任何内容。默认情况下,graphql-java使用logs the exceptions在字段解析期间捕获的ValidationException

您现在有两个选择,您可以在SPQR中注册一个SimpleDataFetcherExceptionHandler来捕获验证异常并记录所需的内容,并向用户返回一个带有错误消息的ResolverInterceptor。因为没有验证异常会冒充到graphql-java,所以DataFetcherResult在这种情况下没有任何事。

它看起来像:

DataFetcherExceptionHandler

请查看the answer here,以获取有关在Spring Boot中注册自定义拦截器的说明。

另一个选择是替换public class ValidationInterceptor implements ResolverInterceptor { @Override public Object aroundInvoke(InvocationContext context, Continuation continuation) throws Exception { try { return continuation.proceed(context); } catch (ValidationException e) { log.warning(e); return DataFetcherResult.newResult() .error(GraphqlErrorBuilder .newError(context.getResolutionEnvironment().dataFetchingEnvironment) .message(e.getMessage()) //the message for the user .build()); } } } graphql-java使用。为此,您必须自己构造DataFetcherExceptionHandler对象并将其注册为Bean。

GraphQL

如果某个地方有Spring功能可用于托管bean的异常处理,我也不会感到惊讶。