Search code examples
node.jsgraphqlapollo

Intercept and customise Apollo GraphQL Errors


I am using simple error handling mechanism based on ApolloError (or derived one) to throw errors from my GraphQL server. For example:

throw new AuthenticationError("Token not present in the request");

In this case, client would receive something like:

{
  "errors": [
    {
      "message": "Token not present in the request",
      ...

I would like to somehow intercept those errors before returning the response to the client, in order to translate them to user's language of choice.

How can I do it?


Solution

  • Looking here you can provide the formatError method to your ApolloServer constructor.

    const server = new ApolloServer({
      typeDefs,
      resolvers,
      formatError: (err) => {
        if (err.message.includes("xyz")) {
          return new Error('Internal server error');
        }
    
        return err;
      },
    });
    

    Use err.originalError to do type checking

    formatError: (err) => {
        if (err.originalError instanceof AuthenticationError) {
          return new Error('Internal server error');
        }
    
        return err;
      },