I'm new to spring graphql and I was trying to implement my own DataFetcherExceptionHandler so I can wrap all exceptions with my custom one.
I've implemented my custom class that implements DataFetcherExceptionHandler but it seems like it still uses the default one, the SimpleDataFetcherExceptionHandler.
How can I make my custom DataFetcherExceptionHandler the default one for the graphql exceptions?
My class:
@Slf4j
@AllArgsConstructor
@Component
public class GraphqlExceptionHandler implements DataFetcherExceptionHandler {
public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) {
Throwable exception = handlerParameters.getException();
SourceLocation sourceLocation = handlerParameters.getSourceLocation();
ResultPath path = handlerParameters.getPath();
MyCustomException error = exposedException(exception, sourceLocation, path);
return DataFetcherExceptionHandlerResult.newResult().error(error).build();
}
@Override
public CompletableFuture<DataFetcherExceptionHandlerResult> handleException(DataFetcherExceptionHandlerParameters handlerParameters) {
return CompletableFuture.completedFuture(this.onException(handlerParameters));
}
Note: I'm not sure if I can use my custom exception like that, but I'm not able to test it while I can't make the exception handler the default one.
With Spring for GraphQL you can implement a
DataFetcherExceptionResolver
or more specifically aDataFetcherExceptionResolverAdapter
that you can for example annotate with@Component
to register it automatically.The
DataFetcherExceptionHandler
fromgraphql-java
is used by Spring for GraphQL internally to delegate to yourDataFetcherExceptionResolver
classes.Inside your own
DataFetcherExceptionResolverAdapter
, you can get the informations that are available asDataFetcherExceptionHandlerParameters
(Path
,SourceLocation
and so on) in aDataFetcherExceptionHandler
from theDataFetchingEnvironment
that is passed toDataFetcherExceptionResolverAdapter
resolveToSingleError
andresolveToMultipleErrors
methods.See here for more informations: https://docs.spring.io/spring-graphql/docs/current/reference/html/#execution-exceptions
You can find an example implementation here: https://github.com/nilshartmann/spring-graphql-training/blob/main/app/publy-backend/src/main/java/nh/publy/backend/graphql/runtime/PublyGraphQLExceptionResolver.java