Exception handling in GraphQLContextFactory #1469
-
Inside my custom GraphQLContextFactory I parse a JWT Token and extract relevant fields into the configmap. This process might fail if the token is not valid or does not meet the specification. When throwing an exception, I would expect my DataFetcherExceptionHandler to handle this exception and return a fitting message to the client. However, the DataFetcherExceptionHandler is not called and instead a wrapped {
"timestamp": "2022-06-15T07:30:45.120+00:00",
"path": "/graphql",
"status": 500,
"error": "Internal Server Error",
"requestId": "3707c8f1-18176"
} What's best practice to catch this exception and wrap it into the default GraphQl error response? I'm using version 5.5.0 with the following minimal example: @Component
class ApplicationGraphQlContextFactory : SpringGraphQLContextFactory<SpringGraphQLContext>() {
override suspend fun generateContextMap(request: ServerRequest): Map<*, Any> {
throw IllegalArgumentException("French fries")
}
override suspend fun generateContext(request: ServerRequest) = SpringGraphQLContext(request)
}
@Component
class ApplicationDataFetcherExceptionHandler : DataFetcherExceptionHandler {
class KotlinGraphQLError(
private val code: Int,
private val message: String?,
) : GraphQLError {
override fun getErrorType(): ErrorClassification = ErrorType.DataFetchingException
override fun getExtensions(): Map<String, Any> = mapOf("code" to code)
override fun getMessage(): String = message ?: ""
override fun getLocations(): List<SourceLocation>? = null
}
override fun onException(handlerParameters: DataFetcherExceptionHandlerParameters): DataFetcherExceptionHandlerResult {
val exception: Throwable = handlerParameters.exception
val error = KotlinGraphQLError(code = 1, message = exception.message)
return DataFetcherExceptionHandlerResult.newResult(error).build()
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hello 👋 Personally I would parse the JWT token in a webfilter and return appropriate HTTP status if it is not valid. |
Beta Was this translation helpful? Give feedback.
Hello 👋
Generation of context happens before the GraphQL execution (link so the handler won't run as this logic is outside of
graphql-java
execution engine.Personally I would parse the JWT token in a webfilter and return appropriate HTTP status if it is not valid.