【问题标题】:Incorrect error handling when using nested try / catch blocks使用嵌套的 try / catch 块时错误处理不正确
【发布时间】:2019-04-23 22:13:26
【问题描述】:
我使用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 错误”时,我会收到“未知错误”,似乎所有错误都传播到最外层的捕获?
有没有办法避免这种或其他允许嵌套错误处理的方法?
【问题讨论】:
标签:
javascript
error-handling
try-catch
propagation
【解决方案1】:
在您的代码中,检查第一个 try 块内是否发生异常。如果是这样,内部尝试将不会被执行。
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")
}
这也是一种可能的情况:
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")
}
希望这会有所帮助:)