async 和 await 如何捕获异常
前言
之前代码写法中使用 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();
}
});
},
参考链接
本文来自博客园,作者:shayloyuki,转载请注明原文链接:https://www.cnblogs.com/shayloyuki/p/17838725.html
posted on 2023-11-17 14:49 shayloyuki 阅读(256) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2022-11-17 在 scss 中使用变量
2022-11-17 el-tree 初始加载中状态
2022-11-17 el-tree 的 setCheckedKeys() 无效