【发布时间】:2019-12-04 12:29:15
【问题描述】:
目前,我正在抛出 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);
}
【问题讨论】:
-
我不知道是否有一种传统的方法可以通过注释或类似的方式委托验证,但对于输入验证,我会抛出 IllegalArgumentException 而不是 RuntimeException,您也可以使用 google Preconditions 进行这些检查
-
你想减少堆栈跟踪的大小吗?这是您想要的吗?如果是,那么您可以覆盖 DataFetcherExceptionHandler 并创建自定义处理程序并挂钩到 GraphQL。
标签: java spring-boot validation graphql graphql-spqr