我正在使用 GraphQL-SPQR 和 Spring Boot 运行 GraphQL API。
目前,我正在抛出RuntimeException
s 以返回 GraphQL 错误。我有一个以正确格式返回错误的customExceptionHandler
实现DataFetcherExceptionHandler
,如下所示:
class CustomExceptionHandler : DataFetcherExceptionHandler {
override fun onException(handlerParameters: DataFetcherExceptionHandlerParameters?): DataFetcherExceptionHandlerResult {
// get exception
var exception = handlerParameters?.exception
val locations = listOf(handlerParameters?.sourceLocation)
val path = listOf(handlerParameters?.path?.segmentName)
// create a GraphQLError from your exception
if (exception !is GraphQLError) {
exception = CustomGraphQLError(exception?.localizedMessage, locations, path)
}
// cast to GraphQLError
exception as CustomGraphQLError
exception.locations = locations
exception.path = path
val errors = listOf<GraphQLError>(exception)
return DataFetcherExceptionHandlerResult.Builder().errors(errors).build()
}
}
我使用CustomExceptionHandler
如下(在我的主应用程序类中):
@Bean
fun graphQL(schema: GraphQLSchema): GraphQL {
return GraphQL.newGraphQL(schema)
.queryExecutionStrategy(AsyncExecutionStrategy(CustomExceptionHandler()))
.mutationExecutionStrategy(AsyncSerialExecutionStrategy(CustomExceptionHandler()))
.build()
}
我想为与异常对应的 UUID 设置一个标头变量,用于记录目的。我该怎么做?
更好的是,是否可以创建一个 Spring Bean 将 UUID 放在所有查询和突变的标头中?
谢谢!