Tracking Errors in Apollo GraphQL with Sentry

Sijuade Ajagunna
2 min readSep 25, 2021

--

Noooo. Not this Sentry… definitely not this Sentry. Image credit: https://bit.ly/3CLotzN

Sentry is an excellent application monitoring and error tracking software. It provides us with some SDKs available for different languages and frameworks, each with provided boilerplate code on its setup and while there’s none specific for Apollo, we can make use of the Node.js SDK and take advantage of the Apollo server plugin feature and its lifecycle events.

Plugins? Lifecycle? What are those?

Plugins provide you with a way to extend the functionality of Apollo Server by creating custom operations in response to lifecycle events, Lifecycle events can be server related, that is, associated with the lifecycle of the server (also called server lifecycle events) or request related (request lifecycle events) which are associated with the request lifecycle.

We’ll make use of the request lifecycle didEncounterErrors to capture our errors and send them to Sentry for tracking. It should be noted that request lifecycle methods should be defined in a server lifecycle request called requestDidStart . This event is fired when the Server starts processing a new request.

now, some code

Here’s a simplified example of how I recently handled error tracking and reporting with Sentry and Apollo Server plugins.

whoa, what’s happening here?

GraphQL Errors are returned in an array. When a request comes into the Apollo Server, it attempts to parse and validate the query/mutation before carrying out the operation. If an error occurs at either of those steps, an error is thrown but the request context does not contain the ‘operation’ key — This is created after validation when the operation is in progress.

Using the extra data provided in the request, operations and the error objects, we can then enrich the error event we send back to Sentry which will make debugging much easier. You can use these properties to determine which errors should be tracked or ignored. You can also add tags to your scope which can provide you with some flexibility when customizing alerts on the Sentry dashboard. You can read more about Sentry scopes here.

--

--