4

I have the following code:

var req = new XMLHttpRequest();
req.onload = function(){
    if (req.status === "200"){
        doSomethingWithTheReceivedData();
    }
    else {
        alert("Error msg");
    }
};

However when running index.html directly from my computer (when it isn't being served from my server) I get "NS_ERROR_DOM_BAD_URI: Access to restricted URI denied" in the Firefox web console of course because the relative path that the script is trying to access isn't available on my computer (it is on my server). Now I want to handle this error correctly, because currently when a user clicks the button that triggers this code nothing happens. I already added the status code check, but that doesn't seem to work for handling this error, I assume a request is never returned? So how do I handle such an error?

Superpelican
  • 85
  • 1
  • 8
  • XHR call to a *file:\\* protocol is restricted. You need to run it on a server. – TaoPR Jul 18 '15 at 14:26
  • @TaoP.R. the question seems to be about handling these errors, and not preventing them – doldt Jul 18 '15 at 14:27
  • So there is no way to handle this error? Because this code is part of an optional feature in my application that only works when the user is using it from a server. Users can also use the application offline (by just downloading a zip archive containing all the necessary files, it is completely client side except for this optional feature). So I want to gracefully handle this error when a user is using the application offline. – Superpelican Jul 18 '15 at 14:29
  • @Dr.Molle unfortunately that didn't work either :( – Superpelican Jul 18 '15 at 14:33

1 Answers1

2

Use a try-catch when you send the request:

try{
  req.send(null);
}catch(e){
 alert(e.message);
}
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201