Skip to content

Instantly share code, notes, and snippets.

@supercede
Last active September 25, 2021 19:10
Tracking Errors in Apollo GraphQL with Sentry
require('dotenv').config();
const { ApolloServer } = require('apollo-server');
const Sentry = require('@sentry/node');
const { makeExecutableSchema } = require('@graphql-tools/schema');
const typeDefs = require('./src/graphql/typedefs');
const resolvers = require('./src/graphql/resolvers');
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
const sentryConfig = {
// server lifecycle event
requestDidStart(_) {
/* Within this returned object, define functions that respond
to request-specific lifecycle events. */
return {
didEncounterErrors(ctx) {
// If we couldn't parse the operation (usually invalid queries)
if (!ctx.operation) {
for (const err of ctx.errors) {
Sentry.withScope(scope => {
scope.setExtra('query', ctx.request.query);
Sentry.captureException(err);
});
}
return;
}
for (const err of ctx.errors) {
// Add scoped report details and send to Sentry
Sentry.withScope(scope => {
// Annotate whether failing operation was query/mutation/subscription
scope.setTag('kind', ctx.operation.operation);
// Log query and variables as extras (make sure to strip out sensitive data!)
scope.setExtra('query', ctx.request.query);
scope.setExtra('variables', ctx.request.variables);
if (err.path) {
// We can also add the path as breadcrumb
scope.addBreadcrumb({
category: 'query-path',
message: err.path.join(' > '),
level: Sentry.Severity.Debug,
});
}
const transactionId = ctx.request.http.headers.get(
'x-transaction-id',
);
if (transactionId) {
scope.setTransaction(transactionId);
}
Sentry.captureException(err);
});
}
},
};
},
};
const serverLocal = new ApolloServer({
schema,
introspection: true,
plugins: [sentryConfig],
});
Sentry.init({ dsn: process.env.SENTRY_DSN, tracesSampleRate: 1.0 });
serverLocal.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment