我使用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错误”时,我都会收到“未知错误”,看来所有错误都传播到了最外面的渔获物上?
有没有一种方法可以避免这种或其他允许嵌套错误处理的方法?
答案 0 :(得分:0)
在您的代码中,检查第一个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")
}
希望这会有所帮助:)