[英]AbortController and fetch: how to distinguish network error from abort error
So I have a fetch with an abort controller like so:所以我有一个中止 controller 的获取,如下所示:
async function fn() {
const abortController = new AbortController();
try {
const response = await fetch(/* ... */, { signal: abortController.signal });
// ...
} catch (e) {
// how can I tell if `e` is from a network error (e.g. offline)
// or an error from an abort
}
}
How can I tell if e
is a.network error or an abort error?我如何判断
e
是网络错误还是中止错误?
abortController.signal.aborted
will tell you if the AbortSignal
fired.会告诉您
AbortSignal
触发。
See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/aborted请参阅https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/aborted
Alternatively if the error name
prop is 'AbortError'
或者,如果错误
name
prop 是'AbortError'
e.name === 'AbortError'
you can detect from the error alone, but beware:您可以单独从错误中检测到,但要注意:
Current version of Firefox rejects the promise with a DOMException
当前版本的 Firefox 拒绝带有 DOMException 的 promise
Therefore, checking abortController.signal.aborted
seems like the safest.因此,检查
abortController.signal.aborted
似乎是最安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.