如何处理Spring Boot中的GraphQl查询验证错误
我使用 spring-boot-starter-graphql
有一个简单的春季启动项目。该项目有一个接受一个参数的控制器。
@Controller
public class HelloNameController {
@QueryMapping
public String hello(@Argument String name) {
return "Hello " + name;
}
}
需要这个论点。
GraphQL模式
type Query {
hello (name : String!) : String
}
在邮递员中调用此API时,请勿通过此参数返回错误。我想覆盖此错误消息的消息,但我找不到方法。 在官方 datafetcherexceptionResolverAdapter ,并且我已将其实现为bean,
@Configuration
public class GraphQLConfig {
@Bean
public DataFetcherExceptionResolver exceptionResolver() {
return DataFetcherExceptionResolverAdapter.from((ex, env) -> {
if (ex instanceof CoercingParseValueException) {
return GraphqlErrorBuilder.newError(env).message("CoercingParseValueException")
.errorType(ErrorType.ExecutionAborted).build();
}
if (ex instanceof CoercingSerializeException) {
return GraphqlErrorBuilder.newError(env).message("CoercingSerializeException")
.errorType(ErrorType.ExecutionAborted).build();
} else {
return null;
}
});
}
}
问题是错误永远不会到达这一点。如何捕获此类错误并覆盖消息?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在github上问了一个类似的问题。来自GraphQL-JAVA项目的响应(#2866 )项目(#415 )是相似的。总结在撰写本文时,这是不可能的。
然后,我创建了一个“解决方法”:
首先,创建一个实现GraphQLerror的自定义异常类。
其次,创建一个实现WebGraphQlinterceptor并将其注释为@Component的interceptor类,因此Spring可以将其创建为bean。此类内部实现逻辑以捕获所需的错误并将其转换为此方法唯一问题之前创建的异常类,
这是所有需要的信息(例如一种错误类型),导致错误的字段等。本机错误消息。因此,要提取所需的参数,我们必须解析字符串消息。
I've asked a similar question on a GitHub. Responses from graphql-java project (#2866) and spring-graphql project (#415) were similar. To summarise at the time of writing it is not possible.
Then I've created a "workaround":
First, create a custom exception class that implements GraphQLError.
Second, create an interceptor class that implements WebGraphQlInterceptor and annotate it as @Component, so Spring can create it as a bean. Inside this class implement logic to catch the needed error and convert it to the exception class created before
The only problem with this approach is that all needed information like a type of an error, the field that causes the error, etc. is embedded in the native error message. So to extract the needed parameters we have to parse the string message.
这是Kotlin中的完整正确错误处理,包括验证验证。
这些错误是由
graphql.execute()
抛出/v22/异常“ rel =“ nofollow noreferrer”>在这里spring 此处
Here's the full proper error handling in kotlin including the validation ones.
Those errors are thrown by
GraphQL.execute()
don't count as "data fetching" errors - documented by GraphQL Java hereThe interceptor is documented by Spring here