6

I have the following piece of code (only relevant parts):

xhttp=new XMLHttpRequest();
xhttp.open("GET",doc_name,false);
xhttp.send();
xmlDoc=xhttp.responseXML;
if(xmlDoc==null)
{
   xmlDoc=loadXMLDoc(defaultXml);
}

This runs fine as I load a default xml file if the specified file does not exist but shows a 404 error only in the console if the file does not exist. (This error does not reflect anywhere in the page except the console).

My question is that how should I check for this exception & is it necessary to add an extra piece of code for checking the existence of the file when the code runs without it?

1

1 Answer 1

6

You can access the HTTP response code via xhttp.status; either a 200 (OK) or 304 (Not Modified) would normally be considered a successful request.

xhttp=new XMLHttpRequest();
xhttp.open("GET",doc_name,false);
xhttp.send();

if (xhttp.status === 200 || xhttp.status === 304) {
    xmlDoc=xhttp.responseXML;
    if(xmlDoc==null)
    {
       xmlDoc=loadXMLDoc(defaultXml);
    }
}

Make sure you're declaring your variables first using var, otherwise you'll have implicit globals, which are bad.

Also make sure you have a good reason for doing this synchronously; synchronous XHR's lock up the browser whilst the request is pending. Making it async is highly recommended.

For the second part of your question, there's no problem what-so-ever; as long as your app can handle the exception. (which is seems to do)

3
  • 1
    yup I know that, I am declaring variables using var & am making it sync (for a reason), the file is small, so making it sync isn't a problem.
    – gopi1410
    Commented May 15, 2012 at 8:35
  • But should I really need to do this checking as the code is running fine without it? Any disadvantages of the error in the console?
    – gopi1410
    Commented May 15, 2012 at 8:35
  • @gopi1410: There's no problem what-so-ever; as long as your app can handle it (which is seems to do).
    – Matt
    Commented May 15, 2012 at 8:36

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.