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?
Add a comment
|
1 Answer
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();
2 Comments
Aleksandr Savvopulo
Please note, that default strategy for mutation is
AsyncSerialExecutionStrategy if you want preserve defaults.retodaredevil
If you want to truely preserve defaults, you're better off setting the exception handler using the
defaultDataFetcherExceptionHandler method.