2

对于常规的 HTTP 请求,我们可以使用 asyncData({error}){...} 创建重定向

我们应该使用什么来使用 Smart Query 重定向到 400 页面?

使用 Vue Apollo,我正在尝试使用

    apollo: {
        queryName: {
            prefetch: true,
            query: wrongQuery,
    
            error(errorData) {
                this.$nuxt.error({
                    statusCode: 500,
                    message: 'Error message',
                });
            },
        },
    };

如果我们重新加载页面,重定向不起作用。我们仍然得到一个错误,因为服务器端渲染:

在此处输入图像描述

使用全局错误处理程序,例如:

    // /plugins/apollo-error-handler.js
    export default ({ graphQLErrors, networkError, operation, forward }, nuxtContext) => {
        console.log(networkError)
        nuxtContext.error({
          statusCode: 404,
          message: 'Error message',
        });
    };

只有错误记录有效。重定向根本不起作用。

我们有什么方法可以处理智能查询中的错误,例如重定向到 400 页?

我们可以在智能查询中捕捉到这样的错误吗?像 try...catch... 在 asyncData() 中防止应用程序崩溃。

4

2 回答 2

2

我在这里找到了解决方案!

export default function ({ redirect }) {
  const link = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors) {
    graphQLErrors.map(({ message }) => {
      if (`${message}` === 'Unauthenticated.') {
        redirect('/login')
        // Do Something
        localStorage.setItem('logged', false)
      }
    })
  }
  if (networkError) {
    console.log(`[Network error]: ${networkError}`)
  }
})
  return {
    defaultHttpLink: false,
    link: ApolloLink.from([link, createHttpLink({
      credentials: 'include',
      uri: 'http://localhost:8000/graphql',
      fetch: (uri, options) => {
        options.headers['X-XSRF-TOKEN'] = Cookies.get('XSRF-TOKEN')
        return fetch(uri, options)
      }
    })]),
    cache: new InMemoryCache()
  }
}`

希望这个答案对你有帮助!
干杯!

于 2021-02-22T12:59:09.627 回答
0

像这样的智能查询非常有限,所以我更喜欢在我的 Vuex 商店中处理它。不确定这是否是最佳做法,但它现在对我很有用。

async niceFancyVuexAction({ dispatch }, { fancyInput }) {
  try {
    const { errors, data } = await this.app.apolloProvider.defaultClient.mutate({
      mutation: yourGraphqlMutationHere,
      errorPolicy: 'all',
      variables: {
        input: fancyInput,
      },
    })

    if (errors) {
      return dispatch('handleErrors', 'we got some errors')
    }

    dispatch('anotherNiceFancyVuexAction', data.Address.createForCompany)
    
    console.log('success !')
  } catch (error) {
    // here, you could catch the error and maybe make a redirect
    dispatch('handleErrors', 'the call was not successfull')
  }
},

否则,onError如果您觉得配置它,使用该链接也是一个好主意:https ://www.apollographql.com/docs/react/data/error-handling/

于 2021-02-16T17:55:28.380 回答