通常在JavaScript中处理async
/await
的错误时,人们默认使用try
/catch
。但是我想知道是否可以改用.catch()
,如下所示:
const res = await fetch().catch((error) => (
// error handling
));
const json = await res.json();
我想知道这是否与
try
/catch
块的工作方式相同。 try {
const res = await fetch()
const json = await res.json();
} catch(e) {
// error handling
}
我知道从技术上讲,try
/catch
块也可以捕获由res.json();
引发的错误,所以我猜还是优先使用.catch()
的例子?
res.json()
。它可能会抛出一个错误,或者什么也不返回,我不确定,但它会导致预期之外的行为。 - Konradthen()
而不是await
,这样你就可以解析 JSON 并捕获任何错误:fetch(bla).then(res => res.json()).catch(err)
。 - Kokodoko