diff --git a/graphql/boot-graphql-webflux/src/main/java/com/example/graphql/exception/CustomExceptionResolver.java b/graphql/boot-graphql-webflux/src/main/java/com/example/graphql/exception/CustomExceptionResolver.java index 073569a98..e9a414b56 100644 --- a/graphql/boot-graphql-webflux/src/main/java/com/example/graphql/exception/CustomExceptionResolver.java +++ b/graphql/boot-graphql-webflux/src/main/java/com/example/graphql/exception/CustomExceptionResolver.java @@ -13,12 +13,16 @@ public class CustomExceptionResolver extends DataFetcherExceptionResolverAdapter @Override protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) { - ConstraintViolationException validationException = (ConstraintViolationException) ex; - return GraphqlErrorBuilder.newError() - .errorType(ErrorType.ValidationError) - .message(validationException.getMessage()) - .path(env.getExecutionStepInfo().getPath()) - .location(env.getField().getSourceLocation()) - .build(); + + if (ex instanceof ConstraintViolationException) { + return GraphqlErrorBuilder.newError() + .errorType(ErrorType.ValidationError) + .message(ex.getMessage()) + .path(env.getExecutionStepInfo().getPath()) + .location(env.getField().getSourceLocation()) + .build(); + } else { + return null; + } } } diff --git a/graphql/boot-graphql-webmvc/src/main/java/com/example/graphql/exception/CustomExceptionResolver.java b/graphql/boot-graphql-webmvc/src/main/java/com/example/graphql/exception/CustomExceptionResolver.java new file mode 100644 index 000000000..e9a414b56 --- /dev/null +++ b/graphql/boot-graphql-webmvc/src/main/java/com/example/graphql/exception/CustomExceptionResolver.java @@ -0,0 +1,28 @@ +package com.example.graphql.exception; + +import graphql.ErrorType; +import graphql.GraphQLError; +import graphql.GraphqlErrorBuilder; +import graphql.schema.DataFetchingEnvironment; +import jakarta.validation.ConstraintViolationException; +import org.springframework.graphql.execution.DataFetcherExceptionResolverAdapter; +import org.springframework.stereotype.Component; + +@Component +public class CustomExceptionResolver extends DataFetcherExceptionResolverAdapter { + + @Override + protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) { + + if (ex instanceof ConstraintViolationException) { + return GraphqlErrorBuilder.newError() + .errorType(ErrorType.ValidationError) + .message(ex.getMessage()) + .path(env.getExecutionStepInfo().getPath()) + .location(env.getField().getSourceLocation()) + .build(); + } else { + return null; + } + } +}