gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:44:35 24 4
gpt4 key购买 nike

目前,我抛出 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);
}

最佳答案

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

对于初学者,我建议使用专用的异常类型,例如 ValidationException,您可以以不同的方式捕获和处理它。

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

您现在有几个选择,您可以在 SPQR 中注册一个 ResolverInterceptor 来捕获验证异常并记录您想要的内容,并返回一个包含错误消息的 DataFetcherResult对于用户来说。由于没有验证异常冒泡到 graphql-java,因此 DataFetcherExceptionHandler 在这种情况下没有任何作用。

它看起来像:

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());
}
}
}

看看the answer here有关使用 Spring Boot 注册自定义拦截器的说明。

另一个选择是替换 DataFetcherExceptionHandler graphql-java 使用。为此,您必须自己构造 GraphQL 对象并将其注册为 bean。

@Bean
public GraphQL graphQL(GraphQLSchema schema) {
GraphQL.Builder builder = GraphQL.newGraphQL(schema)
.queryExecutionStrategy(new AsyncExecutionStrategy(customExceptionHandler))
.mutationExecutionStrategy(new AsyncSerialExecutionStrategy(customExceptionHandler));
return builder.build();
}

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

关于java - GraphQL-SPQR 中返回错误的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57215323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com