0

I'm using XMLHttpRequest to consume APIs on the background. Everything's working fine! My only problem is that when there's no internet, it prints an error message on the console even when it's handled by XMLHttpRequest.onerror

I'm making a PWA that can work offline... it will try to connect but if it failed, that's okay...

Simplified experimental scenarios:

Running the following code shows an error when the internet is disconnected (after installing the app):

let x = new XMLHttpRequest();
x.onload = //do something...
x.onerror = //do another thing...
x.open("GET", "/someresource");
x.send();

And even the following still shows an error when there's no internet:

try {
  let x = new XMLHttpRequest();
  x.onerror = (e) => {
    console.log(
      "Don't worry about anything! \
     This error was handled successfully"
    );
    e.preventDefault();
    return true;
  };
  x.open("GET", "/some-resource");
  x.send();
} catch (e) {
  console.log("It's all under control");
}

Screenshot of the error that should not happen

Which triggers some OCD tendencies for me! I can't sleep before this error is handled...

Menas
  • 1,059
  • 1
  • 9
  • 19
  • https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – Mister Jojo Jul 02 '20 at 20:54
  • Your error is properly handled by the `onerror` handler. The console reports the error to let you know that a network request has failed. However, if you've handled it, you don't have anything to do with that, just ignore it. Those error messages are just the results of your console's verbose-ness... (the `try`..`catch` is not even needed unless you want to guard from synchronous errors as well) – FZs Jul 02 '20 at 21:15
  • @MisterJojo I considered it but I think I need more customizable management over the progress of each request than what the fetch API provides. – Menas Jul 02 '20 at 21:20
  • @FZs Guess you're right. Maybe I should just overcome my OCDs :/ – Menas Jul 02 '20 at 21:20

1 Answers1

0

This is because the error is not thrown, but returned asynchronously. A similar question has been answered here.

Unfortunately, I don't think there's anything you can really do about this. However, the error does not actually stop the script from executing, so it's not really a big deal.