4

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?

1 Answer 1

7

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Please note, that default strategy for mutation is AsyncSerialExecutionStrategy if you want preserve defaults.
If you want to truely preserve defaults, you're better off setting the exception handler using the defaultDataFetcherExceptionHandler method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.