2

I am on the route http://mywebsite.com/[category that doesn't exist] which (per the code below) throws an error. However, I can't seem to get to the catch block in asyncData.

async asyncData({ params, store }) {
  try { 
    await store.dispatch('categories/GET_CATEGORIES')
    await store.dispatch('products/GET_products', params.category)
  } catch(e) {
    console.log(e) // doesn't console log anything
  }
}

Vuex action:

async GET_PRODUCTS({commit}, category) {
  try {
    let url
    if (!category) {
      url = 'some url'
    } else {
      url = 'some other url'
    }

    const response = await this.$axios.$get(url)

    if (!response.length) throw new Error()
    
    commit('some mutation', response.data)
  } catch(e) {
    console.log(e)
  }
}

When I throw the error, shouldn't it also call the catch block in asyncData? The reason why I want to do that is because I want to use the router to navigate to the home page if there is an error in the action.

I have found very little documentation about routing right inside Vuex (its not recommended?). However, asyncData has the context object which includes router.

1
  • 1
    I personally wouldn't consider that bad practice especially since you're catching it elsewhere. If you're concerned about it, you could still rethrow the error from your action. Commented Jan 3, 2021 at 4:34

1 Answer 1

2

Your action is already catching errors and swallowing them.

To allow the caller to handle the error, you could rethrow the error within your action:

async GET_PRODUCTS({commit}, category) {
  try {
    //...
    const response = await this.$axios.$get(url)

  } catch(e) {
    // do something with `e` here...

    // then rethrow error
    throw e
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.