React.js Log all GraphQL queries in Sentry
Asked Answered
H

1

5

I have a React application which I've surrounded with an ErrorBoundary that sends errors to Sentry and it works fine. I would like to log all my GraphQL query errors into Sentry as well but my problem now is for all my GraphQL queries, I have a catch block where I dispatch an action for the failed query. When I remove the catch blocks, the errors are logged into Sentry but I'm unable to trigger the failed query action.

My solution now is to put Sentry.captureException() into each catch block of a GraphQL query which is very repetitive.

Is there a way to allow the ErrorBoundary to still catch GraphQL errors even if the query has it's own catch block?

function getEmployee() {
    return function(dispatch) {
        dispatch(requestEmployeeInformation());

        GraphqlClient.query({ query: EmployeeQuery, fetchPolicy: 'network-only' })
            .then((response) => {
                dispatch(receiveEmployeeInformation(response.data));
            })
            .catch((error) => {
                /* temporary solution. This sends error to sentry but is very repetitive because
                   it has to be added to every single action with a graphql query 
                 */
                Sentry.captureException(error)

                //dispatch this action if the query failed
                dispatch(failGetEmployee(error));
            });
    };
}
Hoang answered 14/2, 2020 at 3:5 Comment(0)
U
8

You can always throw the error again inside the catch block. However, the best way to handle this is by using Error Link. This will allow you to log both GraphQL errors (errors returned as part of the response) as well as network errors (failed requests, invalid queries, etc.).

import { onError } from '@apollo/client/link/error'

const link = onError(({ graphQLErrors, networkError, response }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      Sentry.captureMessage(message)
    )
  if (networkError) {
      Sentry.captureException(networkError)
  }
  
  // Optionally, set response.errors to null to ignore the captured errors
  // at the component level. Omit this if you still want component-specific handling
  response.errors = null
});
Ultramicrochemistry answered 14/2, 2020 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.