javascripterror-handlingxmlhttprequestxmlhttprequest-level2

How do you handle an "Access to restricted URI denied" error in JavaScript when using XMLHttpRequest?


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?


Solution

  • Use a try-catch when you send the request:

    try{
      req.send(null);
    }catch(e){
     alert(e.message);
    }