graphql-java-annotations icon indicating copy to clipboard operation
graphql-java-annotations copied to clipboard

Unwrap InvocationTargetException

Open molexx opened this issue 4 years ago • 2 comments

If an exception is thrown in a method annotated with @GraphQLField the GraphQL response's errors block contains a message about InvocationTargetException, which isn't very useful as it gives no information on the cause and does not allow the method implementation to provide a message to the caller.

InvocationTargetException will contain the real Exception as the 'cause', so if an InvocationTargetException is caught could .getCause() be called on it and the cause thrown upwards please rather than the InvocationTargetException?

molexx avatar Feb 04 '20 17:02 molexx

Maybe it should provide an option to dump log into console when developing?

asinbow avatar Mar 28 '20 04:03 asinbow

I found a workaround. I'm leaving it here if anybody else stumbles upon this issue. You can write a custom GraphQLErrorHandler and unwrap the exception. There is probably a cleaner way to do this, but this works for my use-case.

@Component
public class CustomGraphQLErrorHandler implements GraphQLErrorHandler {
    @Override
    public List<GraphQLError> processErrors(List<GraphQLError> list) {
        return list.stream().map(this::getNested).collect(Collectors.toList());
    }

    private GraphQLError getNested(GraphQLError error) {
        if (error instanceof ExceptionWhileDataFetching) {
            ExceptionWhileDataFetching exceptionError = (ExceptionWhileDataFetching) error;
            Throwable exception = exceptionError.getException();
            if (exception instanceof GraphQLError) {
                return (GraphQLError) exception;
            } else if(exception.getCause() != null && exception.getCause() instanceof InvocationTargetException) {
                InvocationTargetException ite = (InvocationTargetException) exception.getCause();
                if(ite.getTargetException() instanceof GraphQLError) {
                    return (GraphQLError) ite.getTargetException();
                }
            }
        }
        return error;
    }
}

jmostaer avatar Jun 09 '21 15:06 jmostaer

Hi @molexx ,

We're helping with project maintenance and reviewing the list of opened PRs and Issues.

This issue was created quite a while ago, we were wondering if you were still interested in the outcome, please let us know if this is the case.

Without an answer by July 1st, 2023, this issue will be closed as "inactive" (and can always be re-opened later on if needed).

Thanks,

Fgerthoffert avatar Jun 02 '23 08:06 Fgerthoffert