Reputation: 37454
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
Upvotes: 3
Views: 6718
Reputation: 55634
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')
});
}
Upvotes: 7