Spring Graphql - How to use a custom DataFetcherExceptionHandler and override the default one?

2.9k Views Asked by At

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.

1

There are 1 best solutions below

0
On

With Spring for GraphQL you can implement a DataFetcherExceptionResolver or more specifically a DataFetcherExceptionResolverAdapter that you can for example annotate with @Component to register it automatically.

The DataFetcherExceptionHandler from graphql-java is used by Spring for GraphQL internally to delegate to your DataFetcherExceptionResolver classes.

Inside your own DataFetcherExceptionResolverAdapter, you can get the informations that are available as DataFetcherExceptionHandlerParameters (Path, SourceLocation and so on) in a DataFetcherExceptionHandler from the DataFetchingEnvironment that is passed to DataFetcherExceptionResolverAdapter resolveToSingleError and resolveToMultipleErrors 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