wimdeblauwe / error-handling-spring-boot-starter

Spring Boot starter for configurable REST API error handling
https://wimdeblauwe.github.io/error-handling-spring-boot-starter/
Apache License 2.0
430 stars 52 forks source link

Extend the library to handle Graphql errors #78

Closed robertionut95b closed 1 year ago

robertionut95b commented 1 year ago

Hello!

I think the library would grow even more if considered to include GraphQL error handling. There are a few implementations already for java-graphql and Spring framework (DGS, Kickstart, Spring GraphQL, etc.) but not many offer a simple, highly configurable error handling setup.

The main contract from which all error handlers would start is similar to the current implementation:

import graphql.GraphQLError;

public interface GraphqlExceptionHandler {

    boolean canHandle(Throwable throwable);

    GraphQLError handleError(Throwable throwable);
}

The only specific feature would be to implement a specialized bean or extend an ExceptionHandler interface required for the library to work.

Example for DGS:

@Component
public class CustomDataFetchingExceptionHandler implements DataFetcherExceptionHandler {

   @Override
   public CompletableFuture<DataFetcherExceptionHandlerResult> handleException(DataFetcherExceptionHandlerParameters handlerParameters) {
      if (handlerParameters.getException() instanceof MyException) {
         Map<String, Object> debugInfo = new HashMap<>();
         debugInfo.put("somefield", "somevalue");

         GraphQLError graphqlError = TypedGraphQLError.newInternalErrorBuilder()
                 .message("This custom thing went wrong!")
                 .debugInfo(debugInfo)
                 .path(handlerParameters.getPath()).build();

         DataFetcherExceptionHandlerResult result = DataFetcherExceptionHandlerResult.newResult()
                 .error(graphqlError)
                 .build();

         return CompletableFuture.completedFuture(result);
      } else {
         return DataFetcherExceptionHandler.super.handleException(handlerParameters);
      }
   }
}

What do you think about this?

wimdeblauwe commented 1 year ago

I have no experience with GraphQL at all, so this is not something I need. But if you are willing to develop and maintain the feature in such a way that people not using GraphQL are not getting extra dependencies they don't want, then I am willing to review the PR.

robertionut95b commented 1 year ago

A baseline implementation for Spring would require at least spring-graphql.

If this is no issue I might try to invest some time in a PR.

wimdeblauwe commented 1 year ago

I assume we can add it as an optional dependency

robertionut95b commented 1 year ago

Issued #80, thanks!