微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我如何捕捉 nuxt-apollo 错误

如何解决我如何捕捉 nuxt-apollo 错误

我将 apollo 添加到我的 nuxt 项目中。我构建了一个登录,它在登录成功时设置 jwt,但是当它过期时,我收到一个 nuxt 错误。我尝试使用 apollo 错误处理程序捕获 nuxt 错误,但该处理程序不起作用。 我如何才能捕获错误以设置新令牌?

nuxt.config.js
....

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

我的错误处理程序看起来像:

import { Context } from '@nuxt/types'

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

解决方法

我在我的 nuxt.config.js > apollo.clientConfigs.default: '@/plugins/nuxt-apollo-config.js'(不是 errorHandler 所以)中设置了以下内容,它有点适用于我的用例。
不是专家,关于 the documentation 可能有 10 种不同的处理方式。
我按照 Apollo Link overview 设置了以下内容。

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,}
}

不确定它是否有帮助,但这就是我所拥有的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。