nuxt-modules / apollo

Nuxt.js module to use Vue-Apollo. The Apollo integration for GraphQL.
https://apollo.nuxtjs.org
MIT License
956 stars 198 forks source link

Error handling 404/500 in Vuex Store #423

Open realsamanrad opened 2 years ago

realsamanrad commented 2 years ago

When the item not found in graphql server, the nuxt returns 500 statusCode instead of 404. I only want the 500 code when the graphQL host is not rechable.

2021-12-21_160934

/store/products.js

import productGql from '~/queries/getProduct.gql'
export const actions = {
  async getProduct({ commit }, productId) {
    const { data } = await this.app.apolloProvider.defaultClient.query({
      query: productGql,
      variables: {
        id: productId,
      },
    })
}

/pages/product/_id.vue

export default {
  async fetch({ store, error, params }) {
    await store.dispatch('products/getProduct', params.id).catch((err) => {
      error({ statusCode: err.statusCode, message: err.message })
    })
  }
}

nuxt.config.js

export default {
  target: 'server',
  modules: ['@nuxtjs/apollo'],
  apollo: {
    clientConfigs: {
      default: '~/plugins/default-config.apollo.js',
    },
    errorHandler: '~/plugins/error-handler.apollo.js',
  },
}

default-config.apollo.js

export default (context) => {
  return {
    httpEndpoint: 'http://localhost:8000/graphql',
  }
}

error-handler.apollo.js

export default (
  { graphQLErrors, networkError, operation, forward },
  nuxtContext
) => {
  console.log('Global error handler')
  console.log(graphQLErrors, networkError, operation, forward)
}