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. ?
Try 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 computer appears to be offline.");
}
}
};
req.send(payload);
req = null;
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;
}
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.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
Related
I generally have been using XMLHttpRequest to perform Ajax calls. However, when the server has an error, I'd like to console.log the error so that I don't have to run to the server to see the event log there.
Here's what I generally do:
function LoadPage(){
var parameters="this=that";
var x = new GetXmlHttpObject();
x.open("POST", "Ajax.aspx?Function=LoadPage")
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.ontimeout = function () { location.reload(true); }
x.send(parameters);
x.onreadystatechange = function () {
if (x.readyState === 4 && x.status === 200){
//Do Stuff with the response
}
}
But if the server has an error with the request, I get the error on the x.send(parameters) line. I've tried to wrap that in a try..catch, but the error comes up in the console even with the command held inside the try.
How can I console.log the 500 errors from the server using this structure?
But if the server has an error with the request, I get the error on the x.send(parameters) line.
That won't happen. The client can't react to the response in any way before the response has arrived.
I've tried to wrap that in a try..catch
That won't work for two reasons.
It is asynchronous
It doesn't throw an exception
if (x.readyState == 4 && x.status == 200){
You're already testing for a 200 status here. Test for a 500 status in the same way.
Updated function
function LoadPage() {
return new Promise(function(succeed, fail) {
var req = new XMLHttpRequest();
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.open("POST", "Ajax.aspx?Function=LoadPage", true);
req.ontimeout = function () { location.reload(true); }
req.addEventListener("load", function() {
if (req.status < 400)
succeed(req.responseText);
else if (req.status == 500)
fail("Error 500: Internal Server Error");
else
fail(new Error("Request failed: " + req.statusText));
});
req.addEventListener("error", function() {
fail(new Error("Network error"));
});
req.send("this=that");
});
}
Usage:
LoadPage().then(function(text) {
console.log("data.txt: " + text);
}, function(error) {
console.log("Failed to fetch data.txt: " + error);
});
I'm checking if a file at a certain local URL exists via a XMLHttpRequest, kind of a workaround peek at the filesystem. Using the pingFile function described below, I try to see if I get a 200 or 404 for a given file and perform some actions depending on that result.
function pingFile(theURL, callback)
{
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState === this.DONE) {
if (callback !== null) {
return callback(this.status);
} else {
return this.status;
}
}
};
req.open("HEAD", theURL);
req.send();
}
var q = pingFile('images/image1.png', null);
However, when I check the value of q, it is always undefined. I'm missing something about the asynchronous nature of an XHR here, I think, but I haven't been able to find where to wait so that this.status has either of the values I would expect from a file check.
EDIT: I've tried adding return 4; after req.send(); and that always gives q the value 4 regardless of whether the file is there.
How do I get the status value of a XMLHttpRequest back from the function it's in?
For async operations you could use callbacks or promises. Here is a simple example with callbacks:
(function () {
function pingFile(theURL, success, error) {
var req = new XMLHttpRequest();
req.onload = function (e) {
if (this.status === 200) {
success(e);
} else {
error(e);
}
};
req.open("HEAD", theURL);
req.send();
}
function fileExist(e) {
alert('File exist!');
}
function fileNotExist(e) {
alert('File does not exist!');
}
pingFile('images/image1.png', fileExist, fileNotExist);
}());
I have the below code:
sendRequest : function(data){
var me = this;
this._createData(data);
try{
this.req.open(this.method,this.page,true);
this.req.onreadystatechange=function()
{
if (this.readyState==4 && this.status==200)
{
if(this.responseText)
var response = eval('(' + this.responseText + ')');
else
response = null;
me.callBack(response);
return false;
}
}
this.req.send(this.data);
} catch(err){
me.callBack(response);
}
},
It works fine, and returns what I expect it to return, but when the connection is lost, it doesn't go into the catch block. What I want to know is how catch the request when server page is not available.
Here's an example from Microsoft's doc page for onreadystatechange:
function reportStatus()
{
if (oReq.readyState == 4 /* complete */) {
if (oReq.status == 200 || oReq.status == 304) {
alert('Transfer complete.');
}
else {
// error occurred
}
}
}
var oReq = new XMLHttpRequest();
oReq.open("GET", "http://localhost/test.xml", true);
oReq.onreadystatechange = reportStatus;
oReq.send();
Look where it says // error occurred.
There is a similar code example on this MDN documentation page.
I set a setTimeout before I send the Ajax call:
var timeout = window.setTimeout("functionToCallOnTimeout()", 2000);
inside functionToCallOnTimeout I stop the call:
oReq.current=null;
On a positive answer I clear the timeout:
timeout = null;
function connectTo(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
throw "Troubles.";
}
};
xhr.send();
}
try {
connectTo("http://www.google.com");
} catch (e) {
console.log('Exception happend.');
}
Perhaps the "catch" part will execute (in console appears the message), but the exception stays uncatched (= in console appears "Uncaught Troubles.").
Why?
the throw does not bubble up through a callback like that. Pass in an error handling callback and deal with it manually.
Let me illustrate your stack traces
There is no stacktrace connection between the onreadystatechange function and the connectTo function. So when you throw an error it never bubbles up to the try catch block around connectTo.
What firefox is doing is saying "Oh you did something that doesn't work. let me fix that for you and do what you think it does"
function connectTo(url, err) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
err.call(this, new Error("troubles"));
}
};
xhr.send();
}
connectTo("http://www.google.com", function(e) {
console.log(e);
});
I've been trying to get a url to open but I'm miffed as to why this hasn't worked. The code is listed and explained below. Any help will be deeply appreciated.
The object:
function getXMLHTTPRequest() {
var req = false;
try {
/* for Firefox */
req = new XMLHttpRequest();
} catch (err) {
try {
/* for some versions of IE */
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err) {
try {
/* for some other versions of IE */
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err) {
req = false;
}
}
}
return req;
}
The object is called like this:
<script type="text/javascript">
var myDelete = new getXMLHTTPRequest();
</script>
Now here's what I want to do:
function removeArticle(id) {
if (myDelete) {
try {
var deletUrl = "delete.php";
var query = deletUrl + "?theid=" + id;
myDelete.open("GET", query, true);
myDelete.onreadystatechange = removeArticleResponse;
myDelete.send(null);
} catch (e) {
alert ("Unable to connect to the server:\n" + e.toString());
}
} else {
alert ("Bad! Very BAD!");
}
}
When I do this:
if (myDelete.open("GET", query, true)) {
myDelete.onreadystatechange = removeArticleResponse;
myDelete.send(null);
} else {
alert ("No road!");
}
The alert("No road!"); shows me that the code doesn't execute passed this point:
if (myDelete.open("GET", query, true)) {
This means that the if (myDelete) { works. The code passes this stage and for some reason stops here: myDelete.open("GET", query, true); It won't open the url. I'm not sure what the problem is.
Edit: Here's the function used to access the server response:
function removeArticleResponse () {
if (myDelete.status == 4) {
if (myDelete.status == 200) {
try {
response = myDelete.responseText;
document.getElementById('displaynewsletterarticleresult').innerHTML = response;
} catch(e) {
alert("An error occured while reading the response:" + e.toString());
}
} else {
alert ("An error occured when attempting to retrieve the data:\n" + myDelete.statusText);
}
}
}
According to this, XMLHttpRequest.open() has no return value, so your check will always fail.
In your response function, do you mean to check .status == 4 instead of .readyState?
All xmlHTTPRequests are bound to the same origin policy. Maybe that's your issue.
You can read more about it at http://en.wikipedia.org/wiki/Same_origin_policy