Question

I have a code like:

try{
  ...
} catch(error){
  ...
};

In try block, there is a function call that makes a request to a server. When there is no resource on the server, an error is raised (as I can see in Google Chrome's developers tool):

Failed to load resource: the server responded with a status of 404 (Not Found)

and I am trying to catch it in the catch block, but the error is not captured.

Is it a feature of JavaScript that load error is not captured by try catch block?

Was it helpful?

Solution

Typically, when requesting information from a server (for instance, via ajax, by setting the src of an img element, etc.), you don't get an exception, but you do get an error event or callback, not least because the code doing the request finishes before the request does, so it's impossible to throw an exception at that point. Since you haven't shown how you're requesting the information, it's impossible to be more specific, but this is why you're not getting an exception.

For instance, with an ajax request, if there's an error you see the ajax request complete but with the statusCode of the XMLHttpRequest object being an error status code, rather than 200. E.g.:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        // The request is complete; did it work?
        if (xhr.statusCode >= 200 && xhr.statusCode < 300) {
            // Yes
        }
        else {
            // No, got a code outside the 2xx range
        }
    }
};
xhr.open("GET", "/your/url/here", true);
xhr.send();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top