I want to catch all errors with the help of TRY {} CATCH(){} when I send data to a server via XMLHttpRequest.
How can I receive all errors, such as net::ERR_INTERNET_DISCONNECTED
, etc. ?
I want to catch all errors with the help of TRY {} CATCH(){} when I send data to a server via XMLHttpRequest.
How can I receive all errors, such as net::ERR_INTERNET_DISCONNECTED
, etc. ?
- 1 Are you using any javascript frameworks such as jQuery or MooTools? If not, maybe consider it as they have success / error handling built into their AJAX functions as well as taking care of cross browser issues etc. – WizzHead Commented Nov 5, 2014 at 12:08
- 3 Unfortunately, I don't like any frameworks. I wanna use pure JS) – Hit-or-miss Commented Nov 5, 2014 at 12:17
3 Answers
Reset to default 6Try catches didn't work for me. I personally ended up testing for response == "" and status == 0.
var req = new XMLHttpRequest();
req.open("post", VALIDATE_URL, true);
req.onreadystatechange = function receiveResponse() {
if (this.readyState == 4) {
if (this.status == 200) {
console.log("We got a response : " + this.response);
} else if (!isValid(this.response) && this.status == 0) {
console.log("The puter appears to be offline.");
}
}
};
req.send(payload);
req = null;
You should put all the statements which you think that will cause an exception in a try block. After that you can give several catch statements - each one for one exception. In last you can give finally as well - this statement will be executed after Try block regardless of whether or not exception was thrown or caught.
Syntax can be like this:
try{
try_statements
}
[catch (exception_var_2) { catch_statements_1 }]
[catch (exception_var_2) { catch_statements_2 }]
...
[catch (exception_var_2) { catch_statements_N }]
[finally { finally_statements }]
Example:
try {
myroutine(); // may throw three exceptions
} catch (e if e instanceof TypeError) {
// statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
// statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
// statements to handle EvalError exceptions
} catch (e) {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
You can read more here: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
Refer this,
function createXMLHttpRequestObject()
{
// xmlHttp will store the reference to the XMLHttpRequest object
var xmlHttp;
// try to instantiate the native XMLHttpRequest object
try
{
// create an XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
}
catch(e) { }
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}