欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Vue3 + TypeScript + Element Plus 通过 try...catch 捕获不到异常的案例分析

Vue3 + TypeScript + Element Plus 通过 try...catch 捕获不到异常的案例分析

2025/6/13 16:35:13 来源:https://blog.csdn.net/BillKu/article/details/148612066  浏览:    关键词:Vue3 + TypeScript + Element Plus 通过 try...catch 捕获不到异常的案例分析

情况说明:执行 await store.fetchUpdateReagent(reagent); 更新出错,但是没有执行 return

原代码片段:

Reagent.vue

// 更新试剂
const handleUpdateReagent = async (reagent: IReagent) => {// 两个对象不相同,需要更新数据;如果两个对象相同(所有属性值都相同),不需要更新数据if (!isEqual(currentSelectedRow.value, reagent)) {try {// 发送网络请求,更新数据await store.fetchUpdateReagent(reagent);console.log("更新试剂成功");} catch (error) {console.log("更新试剂失败");return;}// 使用浅拷贝,复制对象引用,同步更新页面数据Object.assign(currentSelectedRow.value, reagent);}
};

 /store/index.ts

  // 更新试剂信息const fetchUpdateReagent = async (reagent: IReagent) => {await reagentUpdateService(reagent);};

问题分析:

在您提供的代码中,handleUpdateReagent 函数中的 try-catch 块设计为在 await store.fetchUpdateReagent(reagent) 报错时执行 return。如果报错后没有执行到 return,可能由以下原因导致:

1. fetchUpdateReagent 内部吞没了错误(最常见原因)

typescript

复制

下载

const fetchUpdateReagent = async (reagent: IReagent) => {try {await reagentUpdateService(reagent); // 如果这里报错...} catch (error) {console.log("内部捕获错误"); // ...但被内部捕获且未重新抛出// ❌ 缺少 throw error 或 return Promise.reject(error)}
};

解决方案: 确保内部函数抛出错误:

typescript

复制

下载

const fetchUpdateReagent = async (reagent: IReagent) => {try {await reagentUpdateService(reagent);} catch (error) {console.log("内部记录错误", error);throw error; // 关键!重新抛出错误}
};

2. reagentUpdateService 未正确抛出错误

如果 reagentUpdateService 在失败时未 reject Promise(例如返回错误状态码但未抛出异常):

typescript

复制

下载

const reagentUpdateService = async (reagent) => {const res = await api.update(reagent);if (res.code !== 200) {return { error: "更新失败" }; // ❌ 未触发 catch// 正确做法:throw new Error("更新失败");}
};

3. 异步错误未被等待(语法问题)

确保调用方式正确:

typescript

复制

下载

// ❌ 错误:缺少 await 导致 try-catch 无法捕获
const fetchUpdateReagent = (reagent) => {return reagentUpdateService(reagent); // 必须返回 Promise
};

4. 控制台输出被覆盖

检查浏览器/终端设置:

  • 浏览器控制台是否启用了 "Hide network" 或过滤了日志

  • console.log 输出是否被后续代码覆盖(例如大量日志冲刷)

 核心要点:确保错误在调用链中不被吞没,始终传递到最外层的 try-catch

最终解决方案:

修改 /store/index.ts 中的 fetchUpdateReagent 

  // 更新试剂信息const fetchUpdateReagent = async (reagent: IReagent) => {// 原来的代码:执行报错后,调用者捕获不到异常// await reagentUpdateService(reagent);// 修改方案1:通过 try...catch 捕获异常,重新抛出异常,调用者就可以通过 try...catch 捕获异常// try {//   await reagentUpdateService(reagent);// } catch (error) {//   // 重新抛出异常//   throw error;// }// 修改方案2:直接 return,调用者就可以通过 try...catch 捕获异常return await reagentUpdateService(reagent);};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词