EmreAylanc
EmreAylanc

Reputation: 31

Catch Axios Error within Vuex to Show 404 Page

I am building an app using Django Rest Framework for backend and Vue 3 for frontend. Using Vuex and Vue Router in my project, and also Axios to consume APIs within Vuex actions. However I could not figure out how to show the 404 page when the fetch from backend fails. I tried a couple of things like importing router to vuex and catching the error with router.push({name: 'notfound'}) but it did not worked. Do you have any thoughts about how to achieve this?

router/index.js

...
  {
    path: '/route/:category',
    name: 'filteredterms',
    component: Home
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notfound',
    component: NotFound
  }

store/index.js

import router from "../router/index.js"
...
    async exampleFunc({commit}){
      const response = await axios.get(`http://127.0.0.1:8000/api/exampleEndpoint`)
      .then(response => {
        commit('exampleMutation', response.data)
      })
      .catch(error => {
        if (error.response.status == 404){
          router.push({name: 'notfound'})
      }

Upvotes: 2

Views: 1969

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50787

You can use the interceptor pattern from axios to achieve this globally:

import router from 'path/to/your/router'

axios.interceptors.response.use( 

  //successful callback, we don't need to do anything
  (response) => {
    return response
  }, 

  //check if we received a 404 and redirect
  (error) => {
    if (error.response.status === 404) {
      router.push({name: 'notfound' })
    } else {
      return Promise.reject(error)
    }
  }
)

Upvotes: 2

Related Questions