目前,我正在抛出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);
}发布于 2019-07-31 21:07:15
我不清楚你在问什么..。但我假设您想要自定义要记录的内容。
对于初学者,我建议使用像ValidationException这样的专用异常类型,您可以捕获和处理不同的异常类型。
至于日志记录,它可能发生在grapqh-java中,因为SPQR本身不会记录任何东西。默认情况下,graphql-java使用logs the exceptions在字段解析过程中捕获的SimpleDataFetcherExceptionHandler。
现在您有几个选择,您可以在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上的异常处理,我也不会感到惊讶。
https://stackoverflow.com/questions/57215323
复制相似问题