Anatol Zakrividoroga
Anatol Zakrividoroga

Reputation: 4518

How to Only Catch non-ApolloError Errors with Apollo GraphQL Server

I have an Apollo GraphQL server, where I want to only report internal server errors (not errors extending ApolloError like AuthenticationError, UserInputError, etc.).

Here is the plugin that I wrote that catches internal server errors and reports them:

const errorReportingPlugin = {
    requestDidStart(_) {
        return {
            didEncounterErrors(ctx) {
                // If we couldn't parse the operation, don't do anything
                if (!ctx.operation) return

                for (const err of ctx.errors) {
                    // Don't report errors extending ApolloError like AuthenticationError, UserInputError, etc.
                    if (err instanceof ApolloError) {
                        continue
                    }

                    // report error here...
                }
            }
        }
    }
}

However err instanceof ApolloError returns false when I throw AuthenticationError, which extends ApolloError.

So I tried to check the class of the err by printing the constructor name and I got GraphQLError.

console.log(err.constructor.name)

Does anyone know how to avoid reporting all errors extending ApolloError?

Upvotes: 0

Views: 1199

Answers (1)

Anatol Zakrividoroga
Anatol Zakrividoroga

Reputation: 4518

The solution is to check whether err.originalError (not err) is an instance of ApolloError like this:

if (err.originalError instanceof ApolloError) {
    // don't report error since it is a user facing error like AuthenticationError, UserInputError, etc.
}

credit to @xadm

Upvotes: 1

Related Questions