How do I catch nuxt-apollo errors

Viewed 538

I added to my nuxt project apollo. I build an login which sets the jwt when the login is successful, but when it expried I get an nuxt error. I try to catch the nuxt error with an apollo error handler, but the handler do not work. How am I able to catch the error, to set a new token?

nuxt.config.js
....

  apollo: {
    authenticationType: 'Bearer',
    clientConfigs: {
      default: '~/graphql/config/config.ts'
    },
    errorHandler: '~/plugins/apollo-error-handler.ts',
    tokenName: 'apollo-token'
  }
...

My error handler looks like:

import { Context } from '@nuxt/types'

export default ({ redirect, app, $apolloHelpers, ...rest }: Context) => {
  console.log(1, rest)
}

1 Answers

I've set the following in my nuxt.config.js > apollo.clientConfigs.default: '@/plugins/nuxt-apollo-config.js' (not a errorHandler so) and it kinda works for my use-case.
Not an expert and there are probably 10 differents ways of doing things regarding the documentation.
I followed the Apollo Link overview to set the following.

import { onError } from '@apollo/client/link/error'
import { setContext } from 'apollo-link-context'
import { from } from 'apollo-link'
import { InMemoryCache, IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
import { createHttpLink } from '@apollo/client/core'
import schema from '../apollo/schema.json'
const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData: schema,
})

export default ({ app, $config: { baseUrlGraphql } }) => {
  const headersConfig = setContext(() => ({
    credentials: 'same-origin',
    headers: {
      // ...
    },
  }))

  const link = onError(({ graphQLErrors, networkError, operation, response }) => {
      if (graphQLErrors) {
        graphQLErrors.map(() => console.log('error my dude'))
      }

      if (networkError) {
        console.log('and another one!')
      }
  })

  const cache = new InMemoryCache({ fragmentMatcher, resultCaching: false })

  return {
    defaultHttpLink: false,
    link: from([
      headersConfig,
      link,
      createHttpLink({
        credentials: 'include',
        uri: baseUrlGraphql,
        fetch: (uri, options) => {
          return fetch(uri, options)
        },
      }),
    ]),
    cache,
  }
}

Not sure if it can help anyhow but that's all that I've got.

Related