async 和 await 如何捕获异常

发布时间 2023-11-17 14:51:15作者: shayloyuki

前言

之前代码写法中使用 async 和 await,没有捕获异常,导致不满足 code === 200 条件时,页面无法抛出错误,如下所示:

async 和 await
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (!valid) return;
        this.btnLoading = true;
        if (this.moduleType === "add") {
          const data = await addInStan(this.form);
          if (data.code === 200) {
            this.$message.success("新增成功");
            this.cancel();
            this.loadInStans();
          } else {
            this.btnLoading = false;
          }
        } else {
          const data = await editInStan(this.form);
          if (data.code === 200) {
            this.$message.success("编辑成功");
            this.cancel();
            this.loadInStans();
          } else {
            this.btnLoading = false;
          }
        }
      });
    },

后来采取了 .then().catch() 的写法,如下所示。但还是觉得不如 async 和 await 简洁。

.then().catch()
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) return;
        this.btnLoading = true;
        if (this.moduleType === "add") {
          addInStan(this.form)
            .then(() => {
              this.$message.success("新增成功");
              this.cancel();
              this.loadInStans();
            })
            .catch(() => (this.btnLoading = false));
        } else {
          editInStan(this.form)
            .then(() => {
              this.$message.success("编辑成功");
              this.cancel();
              this.loadInStans();
            })
            .catch(() => (this.btnLoading = false));
        }
      });
    },

再后来,看到了 try{} catch(err){} 的写法,如下所示,也能捕获异常。但代码也不够简洁。

try{} catch(err){}
    async querySearch(queryString, cb) {
      try {
        let para = {
          ...this.additionParas,
          [this.searchKey]: queryString,
        };
        if (this.isScrollPage) {
          // 输入框失去焦点后再次获焦时,重置页码
          this.pageNum = 1;
          para.pageNum = this.pageNum;
        }
        let { data } = await queryData(para, this.queryUrl);
        if (data.rows) {
          let arr = [];
          data.rows.forEach((item) => {
            // 下拉框选项要转为字符串,避免选择后,导致 autocomplete 组件绑定值为数字而报错
            arr.push({ [this.valueKey]: item.toString() });
          });
          // 若有数据,则显示,否则隐藏下拉框
          if (arr.length) {
            this.$refs[this.refName].activated = true;
            cb(arr);
          } else {
            // 无数据,不显示下拉框
            cb([]);
          }
        }
        this.total = data.totle || 0;
      } catch (err) {
        console.log({ err });
      }
    },

解决

直接 await interfaceName(para).catch((err) =>{}) 就可捕获异常。

相关代码
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (!valid) return;
        this.btnLoading = true;
        if (this.moduleType === "add") {
          const data = await addInStan(this.form).catch(
            () => (this.btnLoading = false)
          );
          if (data.code !== 200) return;
          this.$message.success("新增成功");
          this.cancel();
          this.loadInStans();
        } else {
          const data = await editInStan(this.form).catch(
            () => (this.btnLoading = false)
          );
          if (data.code !== 200) return;
          this.$message.success("编辑成功");
          this.cancel();
          this.loadInStans();
        }
      });
    },

参考链接

不是吧?async/await异常捕获你还在用try-catch~