Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  48] [ 6]  / answers: 1 / hits: 21780  / 10 Years ago, wed, august 20, 2014, 12:00:00

I'm making an http request asynchronously using XMLHttpRequest:



xhr.open(method, uri, true);


When I send something:



xhr.send(something)


When the server is down, it throws the following error:



net::ERR_CONNECTION_REFUSED


How can I catch and handle this error? The standard try..catch block doesn't work as the request is asynchronous.



Thanks in advance.


More From » html

 Answers
1

Use the onerror event of the XMLHttpRequest:



function aGet(url, cb) {
var x = new XMLHttpRequest();
x.onload = function(e) {
cb(x.responseText)
};
x.onerror= function(e) {
alert(Error fetching + url);
};
x.open(GET, url, true);
x.send();
}

var dmp = console.log.bind(console); // Dummy callback to dump to console
aGet(/, dmp) // Ok, uses onload to trigger callback
aGet(http://dgfgdf.com/sdfsdf, dmp); // Fails, uses onerror to trigger alert

[#69718] Monday, August 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;