Duston
Duston

Reputation: 1641

Getting the error text in an XMLHttpRequest error call back

Given this little snippet of code:

function getPage () {
        var xhttp = new XMLHttpRequest();
        xhttp.addEventListener("error", getFailed);
        xhttp.open("GET", "http://nonexistentserver.com", true);
        xhttp.send();
        }

function getFailed(msg) {
    // I get an ProgressEvent object which doesn't have any text properties?
        }

When it runs, the getFailed() callback does indeed get called, but I can't find any information on how to determine what the error was. When I searched for information, all I could find were HTML errors (like 404) and bug reports about causing an error. How do I obtain information about what the failure was available in the error callback?

Upvotes: 4

Views: 5790

Answers (3)

Vishwa Pandey
Vishwa Pandey

Reputation: 1

In the getFailed call:

function getFailed(e) {
    console.log('response error:', e.currentTarget.response);
}

The e.currentTarget is the same xhr instance.

Upvotes: 0

Cleiton Tortato
Cleiton Tortato

Reputation: 113

You can try to use onprogress event and handle the status code, like this:

var xhr = new XMLHttpRequest;
xhr.onprogress = function () {
  console.log(xhr.status); //404 will be printed on console
};

xhr.open('GET', '/noexists');
xhr.send(); 

Upvotes: 0

Andrew Dashkov
Andrew Dashkov

Reputation: 311

It seems like in your case it's impossible to get the error information. There are some properties which show the request status: XMLHttpRequest.status, XMLHttpRequest.statusText and XMLHttpRequest.responseText. But they all don't work here (only XMLHttpRequest.status shows '0') in this case. Error event of XMLHttpRequest is called when just error occurs. It doesn't send any information about the error. I hope these will help you: XMLHttpRequest and XMLHttpRequest Properties

Upvotes: 2

Related Questions