vue中@Action的异常处理

2020-01-17  本文已影响0人  阿金的故事

1. 知识点:

  1. 在某行代码有错误抛出后,后面的代码都不会被执行,直接阻断
  2. try-catch 语句里的代码有一行有错误,后面也阻断,但是跳出 catch 语句后面的代码依然可以执行,因为抛出的错误被 catch 接到了
 try {
    test()
    console.log('after-test');
  } catch (e) {
    console.log('catch-error', e);
  }
  console.log('after-trycatch');
  function test() {
    throw new Error()
  }

2. 问题来源

//页面请求接口
try {
      await this.fetchR(params)
    } catch (e) {
      if (e && e.isHandled) {
        return
      }
      this.$message.error('获取失败')
    }

//store里请求数据
 @Action({ rawError: true })
  async fetchR(
    params: params,
  ): Promise<R[]> {
    const url = api.v.r()
    const response = await axios.post(url, params)
    const { data } = response
    this.context.commit('setR', {
      type: params.type,
      data,
    })
    return data
  }

可知:@Action 在不给 rawError 置为 true 时,会 new 一个新的 Error,并且带上 aciton 里抛出的错误,包裹到一起抛出,因此页面 catch 住的 error 是@Action 抛出的错误,打印就会看到原 error 的信息

3. 对当前项目的启示

需要成功获取接口数据后才更改某一状态或者某一数据值的,不应该将代码写在 trycatch 后,因为即使抛出错误,catch 后的代码也会被执行,所以对于这种代码可以写在 try 语句里,await 后。
比如:页面打 tag,需要在成功将 tag 传给后台成功后再变为选中的蓝色状态,以及做后面的操作。

参考:https://github.com/championswimmer/vuex-module-decorators/issues/26
https://github.com/championswimmer/vuex-module-decorators/blob/master/src/action.ts

上一篇 下一篇

猜你喜欢

热点阅读