简体   繁体   English

Nuxt 和 Vue Apollo。 如何通过重定向到 404/400/500 错误页面来处理 Smart Query 中的错误? 我们能捕捉到这样的错误吗?

[英]Nuxt and Vue Apollo. How to handle errors inside Smart Query with redirection to 404/400/500 error page? Can we catch such errors?

With regular HTTP request, we may create redirection with asyncData({error}){...}对于常规的 HTTP 请求,我们可以使用 asyncData({error}){...} 创建重定向

What should we use for redirecting to 400 page using Smart Query?我们应该使用什么来使用 Smart Query 重定向到 400 页面?

With Vue Apollo, I am trying to use使用 Vue Apollo,我正在尝试使用

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

In case if we reload the page, redirection doesn't work.如果我们重新加载页面,重定向不起作用。 We still got an error becouse server side rendering:我们仍然得到一个错误,因为服务器端渲染:

在此处输入图像描述

With global error handler like:使用全局错误处理程序,例如:

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

Only errors logging works.只有错误记录有效。 Redirection doesn't work at all.重定向根本不起作用。

Do we have any way to handle errors inside smart queries with redirection to 400 page for example?我们有什么方法可以处理智能查询中的错误,例如重定向到 400 页?

Can we catch such errors in smart query?我们可以在智能查询中捕捉到这样的错误吗? Like try...catch... in asyncData() to prevent app crash.像 try...catch... 在 asyncData() 中防止应用程序崩溃。

I found the solution here !我在这里找到了解决方案!

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()
  }
}`

Hopefully this answer helpful for you!希望这个答案对你有帮助!
Cheers!干杯!

The smart query like this is pretty limited and so, I prefer to handle it in my Vuex store.像这样的智能查询非常有限,所以我更喜欢在我的 Vuex 商店中处理它。 Not sure if it's the best practice but it works great for me right now.不确定这是否是最佳做法,但它现在对我很有用。

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

Otherwise, yeah using the onError link is also a good idea if you feel configuring it: https://www.apollographql.com/docs/react/data/error-handling/否则,如果您觉得配置它,使用onError链接也是一个好主意: https://www.apollographql.com/docs/react/data/error-handling/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Nuxt.js 中捕获服务器错误,以免页面渲染崩溃? (Vue) - How to catch server errors in Nuxt.js so it doesn't crash page render? (Vue) 如何处理500个错误 - How to handle 500 errors 我们可以使用JS中的catch(error)处理http(4XX-5XX)的所有错误情况吗? - Can we handle all the errors scenarios of http (4XX-5XX) using catch(error) in JS? 如何使用React-Apollo处理GraphQL错误? - How to handle GraphQL errors with React-Apollo? 如何处理 express api 中的多个错误?就像我想处理 404,405,400 和 500 - how to handle multiple error in express api?like i want to handle 404,405,400 and 500 为什么 WebStorm 在 Vue 组件或 .grapgql 文件中的 apollo 对象内的 gql 查询中显示错误 - Why WebStorm show errors in gql query inside apollo object in Vue component or .grapgql files 如何在不使用Ember进行URL重定向的情况下处理错误 - How to handle errors without URL redirection with Ember 如何处理 catch 中的错误 - vue.js - How to handdle the errors in catch - vue.js 如何处理 try/catch 之外的错误? - How to handle errors outside try/catch? Angular / rxJS:combineLatest - 如何处理 404 错误 - Angular / rxJS: combineLatest - how to handle 404 Errors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM