[英]Is it ok to mix .catch() with async/await for error handling?
Normally when it comes to error handling for async
/ awai
t in JavaScript, people default to use try
/ catch
.通常,当涉及到
awai
中的async
/ await 错误处理时,人们默认使用try
/ catch
。 But I wonder if I can use .catch()
instead, as in但我想知道我是否可以使用
.catch()
代替,如
const res = await fetch().catch((error) => (
// error handling
));
const json = await res.json();
I wonder if this works the same as a try
/ catch
block我想知道这是否与
try
/ catch
块相同
try {
const res = await fetch()
const json = await res.json();
} catch(e) {
// error handling
}
I understand that technically the try
/ catch
block can catch errors raised from res.json();
我知道从技术上讲,
try
/ catch
块可以捕获从res.json();
as well, so I guess it is still preferable to the .catch()
example?同样,所以我想它仍然比
.catch()
示例更可取?
I wonder if this works the same as
try
/catch
block我想知道这是否与
try
/catch
块相同
No - as you've already answered yourself.不 - 因为你已经回答了自己。 In particular, the
try
block around res.json()
would also catch errors thrown from that, which you may or may not want .特别是,
res.json()
周围的try
块也会捕获由此引发的错误,您可能想要也可能不想要。
Also, if you aren't re- throw
ing an exception from your .catch()
callback, its return value will become the res
value and res.json()
is still called on it, so you better return
a valid Response
instance.此外,如果您没有从
.catch()
回调中重新throw
异常,它的返回值将变为res
值,并且仍会调用res.json()
,因此您最好return
一个有效的Response
实例。
Is it ok to mix
.catch()
withasync
/await
for error handling?可以将
.catch()
与async
/await
混合以进行错误处理吗?
Yes, absolutely.是的,一点没错。 It's a much more versatile tool if you want to handle errors from one specific promise only.
如果您只想处理来自一个特定 promise 的错误,它是一种更通用的工具。 Doing that with
try
/ catch
is much more ugly , so I would even recommend using .catch()
for re-throwing errors (when you want a better error message):使用
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();
If you don't want to re- throw
, I recommend using .then()
to handle success and failure paths separately :如果您不想重新
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.