javascript - 使用嵌套的 try / catch 块时错误处理不正确
问题描述
我使用块设置了错误处理try/catch
,其简化形式如下所示
try {
// .. Some application logic
try {
// .. some async api code
} catch (e) {
throw new Error("Api Error")
}
return true;
} catch (e) {
throw new Error("Unknown Error")
}
问题是,每当我期望返回“Api Error”时,我会得到“Unknown Error”,似乎所有错误都传播到最外层的捕获?
有没有办法避免这种或其他允许嵌套错误处理的方法?
解决方案
In your code, check if exception is happening inside the first try block. If so, the inner try won't be executed.
try {
// .. Some application logic
// exception occurs here
// below code is not executed and the control is given to catch block
try {
//this did not execute
// .. some async api code
} catch (e) {
throw new Error("Api Error")
}
return true;
}
catch (e) {
//control came here
throw new Error("Unknown Error")
}
This is also a possible case:
try {
// .. Some application logic
// no exceptions occur here
// below code is executed
try {
//this did not execute
//exception here
// .. some async api code
} catch (e) {
//control came here and this threw APIerror
throw new Error("Api Error")
}
//this did not execute as the previous catch block raised another exception
return true;
}
catch (e) {
//control came here
throw new Error("Unknown Error")
}
Hope this helps :)
推荐阅读
- javascript - 未捕获的类型错误:在 Chrome 控制台中运行 JavaScript 时无法读取 null 的属性“子项”
- spring-boot - Flyway 6 JavaMigrations with Native Dependency Injection for Spring Beans
- sql - SQL Server 中的字符填充
- php - 如何使用 PHP 从 URL 中获取值?
- google-cloud-platform - 数据流用例(小型 SQL 查询)
- google-visualization - 谷歌水平条形图注释重叠 vAxis
- python-3.x - 如何从 tweepy 获取完整的推文?
- oracle - 如何在 Talend 的子作业中捕获数据库错误
- javascript - 在不使用 jQuery 的情况下突出显示活动锚链接
- html - 如何将 html 嵌入 Data Studio