如何捕获异步函数调用的错误?(Vue3+Pinia场景)
如何捕获异步函数的错误
问题原因
你在getAccount的catch块里返回了错误数据,而非抛出错误。对于async函数来说,只要内部没有主动抛出异常,无论return任何值,它返回的Promise都会处于resolved状态,所以外部的.catch()永远不会触发,所有结果都会走到.then()里。
解决方案
方案1:让外部捕获错误(推荐)
修改Pinia store里的getAccount函数,在catch块中抛出错误,而非返回:
const getAccount = async(id, month, year) => { try { getData.defaults.headers.common['__authorization__'] = UserStore.jwt const response = await getData.get(`/use/b/comptes/${id}/${month}/${year}`) if (response.status === 200) { // 更新store状态 return true } return false } catch (error) { // 抛出错误,使Promise变为rejected状态 throw error.response.data } }
此时组件里的.catch()就能正常捕获到错误:
watchEffect(() => { if (route.name === 'comptes') { getAccount( compte.value.id, route.params.month, route.params.year ) .then(result => { console.log('结果', result) }) .catch(err => { console.log('捕获到错误', err) }) } })
方案2:内部处理错误,外部通过返回值判断
如果需要在store内部处理错误,但外部要区分成功/失败状态,可以返回一个包含状态标识的对象:
const getAccount = async(id, month, year) => { try { getData.defaults.headers.common['__authorization__'] = UserStore.jwt const response = await getData.get(`/use/b/comptes/${id}/${month}/${year}`) if (response.status === 200) { // 更新store状态 return { success: true, data: true } } return { success: true, data: false } } catch (error) { // 返回错误状态的对象 return { success: false, error: error.response.data } } }
组件中通过判断返回值的success字段区分状态:
watchEffect(() => { if (route.name === 'comptes') { getAccount( compte.value.id, route.params.month, route.params.year ) .then(result => { if (result.success) { console.log('操作成功', result.data) } else { console.log('错误信息', result.error) } }) } })
原理补充
async函数返回的Promise状态由内部逻辑决定:
- 执行
return时,Promise进入resolved状态,外部通过.then()接收返回值 - 执行
throw时,Promise进入rejected状态,外部通过.catch()捕获异常
你的原代码中,catch块返回错误数据,相当于把异常转化成了正常返回值,因此外部的.catch()永远不会被触发。
内容的提问来源于stack exchange,提问作者thiebo
相关产品推荐
相关产品推荐

