Search code examples
javaspring-mvcexceptiongraphqlgraphql-java

How to implement exception handler for GraphQL in Spring


I'm building web application that is using GraphQL with leangen graphql-spqr.
I have problem with exception handling. For example inside service class I'm using spring bean validation that checks for some validity and if its not correct, its throwing ConstraintViolationException.
Is there any way to add some exception handler that would send proper message to the client? Something like ExceptionHandler for controllers in rest api? Or maybe it should be done in other way?


Solution

  • Solution I have found is to implement DataFetcherExceptionHandler, override onException method and set it as default exception handler.

    public class ExceptionHandler implements DataFetcherExceptionHandler {
    
        @Override
        public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) {
    
        Throwable exception = handlerParameters.getException();
    
        // do something with exception
    
        GraphQLError error = GraphqlErrorBuilder
                .newError()
                .message(exception.getMessage())
                .build();
    
        return DataFetcherExceptionHandlerResult
                .newResult()
                .error(error)
                .build();
        }
    }
    

    and to set it as default exception handler for querys and mutations

    GraphQL.newGraphQL(someSchema)
                .queryExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))
                .mutationExecutionStrategy(new AsyncExecutionStrategy(new ExceptionHandler()))
                .build();