![](/img/trans.png)
[英]JavaScript: differences between async error handling with async/await and then/catch
[英]Is it ok to mix .catch() with async/await for error handling?
通常,当涉及到awai
中的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()
示例更可取?
我想知道这是否与
try
/catch
块相同
不 - 因为你已经回答了自己。 特别是, res.json()
周围的try
块也会捕获由此引发的错误,您可能想要也可能不想要。
此外,如果您没有从.catch()
回调中重新throw
异常,它的返回值将变为res
值,并且仍会调用res.json()
,因此您最好return
一个有效的Response
实例。
可以将
.catch()
与async
/await
混合以进行错误处理吗?
是的,一点没错。 如果您只想处理来自一个特定 promise 的错误,它是一种更通用的工具。 使用try
/ catch
这样做会更难看,所以我什至建议使用.catch()
重新抛出错误(当你想要更好的错误消息时):
const res = await fetch(…).catch(error => {
throw new Error('Could not reach backend', {cause: error});
});
if (!res.ok) throw new Error(`Backend responded with ${res.status} error: ${await res.text()}`);
const data = await res.json();
如果您不想重新throw
,我建议使用.then()
分别处理成功和失败路径:
const data = await fetch(…).then(res => {
if (!res.ok) {
console.error(`Backend responded with ${res.status} error`);
return null;
}
return res.json();
}, error => {
console.error('Could not reach backend', error);
return null;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.