3

I have an async action, like so:

export const fetchTweets = async ({ commit, state }) => {
  const tweetFetchError = error => {
    // throw here?
  }
  try {

    const { oAuthAccessToken, oAuthAccessTokenSecret, user: { id } } = state

    const { data, errors } = await api.fetchTweets(oAuthAccessToken, oAuthAccessTokenSecret, id)

    if (errors && Object.keys(errors).length) return tweetFetchError(errors)

    commit(types.SET_TWEETS, {
      tweets: data
    })
  } catch (error) {
    tweetFetchError(error)
  }
}

Which I invoke from my Component, like so:

methods: {
    ...mapActions(['fetchTweets']),
    async handleFetchTweets () {
      try {
        await this.fetchTweets()
      } catch (error) {
        console.log('errored')
        this.$message.error('Error fetching tweets')
      }
    }
},

I call handleFetchTweets in mounted.

My question is, how can I catch the error back in the Component? In the Action, this method tweetFetchError gets correctly invoked when there's an error, but I'm unsure how to trigger the catch in the try/catch back in the Component

1 Answer 1

7

You need to throw the error after you've caught it in the fetchTweets method:

  ...
  } catch(error) {
    tweetFetchError(error)
    throw error;
  }
}

And catch the error using the returned Promise's .catch handler:

async handleFetchTweets () {
  await this.fetchTweets().catch((error) => {
    console.log('errored')
    this.$message.error('Error fetching tweets')
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

When I do this, I don't get 'errored' in the console (which would suggest my catch worked in the Component, but I simply see Uncaught (in promise) Error: Network Error at createError (createError.js?f777:16) at XMLHttpRequest.handleError (xhr.js?14ed:87)
Oh yeah, since it's an async method it's returning a Promise, so you need to use the Promise's catch method instead of a try/catch. See my edit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.