Skip to content

Instantly share code, notes, and snippets.

@eladchen
Created July 10, 2020 07:06
Show Gist options
  • Save eladchen/00251cfd96a3fc4fe0c986d83fd48bc2 to your computer and use it in GitHub Desktop.
Save eladchen/00251cfd96a3fc4fe0c986d83fd48bc2 to your computer and use it in GitHub Desktop.
An example of how to access apollo context in formatError() method.
import { Request, Response } from "express";
import { GraphQLError, GraphQLFormattedError } from "graphql";
import { GraphQLServerOptions } from "apollo-server-core/src/graphqlOptions";
import { ApolloServer, ApolloServerExpressConfig as C } from "apollo-server-express";
export type FormatError = (graphQLError: GraphQLError, context: unknown) => GraphQLFormattedError;
export type ApolloServerExpressConfig = Omit<C, "formatError"> & {
formatError?: FormatError;
};
/**
* A modified instance of apollo express server class
* that calls formatError() method with the context value.
*/
export class CustomApolloServer extends ApolloServer {
constructor(config: ApolloServerExpressConfig) {
super(config as C);
}
async createGraphQLServerOptions(req: Request, res: Response): Promise<GraphQLServerOptions> {
const options = await super.createGraphQLServerOptions(req, res);
if (typeof options.formatError === "function") {
const formatError = options.formatError as FormatError;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
options.formatError = (graphQLError: GraphQLError) => {
return formatError(graphQLError, options.context);
};
}
return options;
}
}
@galvin96
Copy link

Hi @eladchen ,
I think you could consider about the didEncounterErrors event which fires when Apollo Server encounters errors while parsing, validating, or executing a GraphQL operation. The errors are available on requestContext.errors.
E.g.

const errorLoggerMiddleware = {
  requestDidStart() {
    return {
      async didEncounterErrors(requestContext) {
        console.error("☝ User data", requestContext.contextValue?.user);
      }
    };
  }
};
const server = new ApolloServer({
    ...
    plugins: [
      errorLoggerMiddleware,
    ]
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment