Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to capture `DOMException: Aborted` from AbortController in an IF statement?

I'm using an AbortController and catching the error it throws when it aborts. My debugger says that the error is DOMException: Aborted. I want to capture that in an IF statement, but I'm not sure how. I tried if (e == "DOMException: Aborted") and if (e == "Aborted") but they don't capture it.

My code:

  controller = new AbortController();
  const signal = controller.signal;
  fetch(url, { signal })
    .then(function(response) {
      console.log('Download complete', response);
    })
    .catch(function(e) {
      console.log('Download error: ' + e.message);
    });

then I abort this controller with controller.abort()

like image 920
gkeenley Avatar asked Apr 22 '26 05:04

gkeenley


1 Answers

It's a DOMException instance, an object not a string. The proper condition to test for it is

.catch(function(e) {
  if (e instanceof DOMException && e.name == "AbortError") {
    // …
  } else {
    console.log('Download error: ' + e.message);
  }
});

You can also check whether e.code == DOMException.ABORT_ERR.

like image 89
Bergi Avatar answered Apr 24 '26 17:04

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!