我的理解是,一段在调用堆栈中任何地方抛出错误的代码都可以在最终的 catch 块中被捕获。对于获取错误,当没有互联网可用时,当我在 callCallAPI 中创建 APIwithoutCatch 时,未捕获到错误。而 APIwithCatch 捕获自己的错误。所有其他错误,例如 404,都在我想要的任何地方都被捕获。
async function APIwithcatch() {
try {
var response = await fetch("http://wwww.dfdfdf.com/user.json");
return response;
} catch (e) {
console.log(e);
}
}
async function APIwithoutcatch() {
var response = await fetch("http://wwww.dfdfdf.com/user.json");
return response;
}
function callCallAPI() {
try {
// return APIwithcatch();
return APIwithoutcatch();
} catch (e) {
console.log(e);
}
}
callCallAPI();
我假设任何错误都应该流向调用堆栈是否正确? net::ERR_INTERNET_DISCONNECTED 错误有什么特别之处?
原文由 DrEarnest 发布,翻译遵循 CC BY-SA 4.0 许可协议
APIwithoutcatch
是一个async function
它不会抛出异常但会拒绝它返回的承诺。 You need to wait for the promise, either withthen
orawait
syntax (just like you didawait
thefetch
withinAPIwithcatch
):