throwing and catching exception from function - javascript

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);
});

Related

Returning original post data if request fails

I know I could just do this with a global, but I'd like to be object oriented if I can. If my request response returns a false for that 'ok' value, I'd like to log the data that was originally posted. Is that data accessible by a listener function on the request object?
Thanks!
function reqListener () {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
//Here I want to log the data that I originally posted
console.log(__TheFormDataThatWasPassedtoSend__);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load",reqListener);
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
So the problem you have is needing to use data known when you create the eventListener when the eventListener actually fires. Below is your code to do this with formData
function reqListener (formData) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
console.log(formData);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() { reqListener.call(this,formData) });
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);

Troubles with JSON in JavaScript

I have something weird and cannot find out what is causing it.
I have a global array variable defined, tmpMs. I fill it using AJAX and JSON.parse, that works:
function LoadMobs(dung){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} else {
throw new Error("Ajax is not supported by this browser");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
// get mobs from PHP
setTempMobs(JSON.parse(xhr.responseText));
alert(tmpMs[0].NAME);
}
}
}
xhr.open('POST', 'loadmobs.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("dung=" + dung);
}
function setTempMobs goes here:
function setTempMobs(mss){
tmpMs = mss;
}
The alert function within the AJAX works and displays the name of the mob. No surprise.
However if I want to access the "tmpMs" variable right behind the LoadMobs function, it says "Cannot access property 0 of undefined"
LoadMobs(currDungBgIndex);
alert(tmpMs[0].NAME);
Any idea would be appreciated. Maybe I should mention that all this is happening within some canvas redrawing interval.

onreadystatechange only firing once

I have the following code for my request:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) // state of 4 is 'done'. The request has completed
{
callback(req.responseText); // The .responseText property of the request object
} else { // contains the Text returned from the request.
console.log(req.readyState);
}
};
req.open("GET", url, true);
req.send();
However, the readyState is changing to 1 and firing correctly (I'm seeing it echoed in the console) but it simply won't progress to 2. After awhile it times out and I get this in the console:
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
Uncaught SyntaxError: Unexpected end of input
Anyone have any idea why this might be?
Put this
req.open("GET", url, true);
req.send();
above this line
req.onreadystatechange = function() {
Sorry all, this ended up being a VPN issue, not a scripting one.
function getLatestfileinAllPath(urls)?
{
for(i = 0;i<urls.length;i++){
run(i)
}
function run(){
var request = new XMLHttpRequest();
request.open('POST', url[i]);
request.send(JSON.stringify({"data":"some data"}));
request.onreadystatechange = function()
{
if (request.readyState === XMLHttpRequest.DONE && request.status == 200)
{
console.log(JSON.parse(request.response));
}
}
};
}
}

How to catch errors involving XmlHttpRequest?

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

Ajax - Function to check if url exists before send request

I am writing a function to grab a json file from a website/server and save it in local storage with the code:
function donators() {
var jsonURL = "http://mywebsite.com/donators.json";
var xhr = new XMLHttpRequest();
xhr.open("GET", jsonURL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
localDataStore.set("fb_donators", xhr.responseText);
}
};
xhr.send();
}
The above code works perfectly fine when the json file can be reached, but if my server goes down and the file cannot be reached my script halts at the line with xhr.send() with the error:
GET http://mywebsite.com/donators.json net::ERR_NAME_NOT_RESOLVED
Is there a way I can detect check if url can be reached before the send request to stop the send the request and allow the rest of my script to continue to run instead of getting halted at xhr.send()?
Thanks!
You can use a try block for this. It still requires the HTTP request, but it will fail gracefully and you can handle the error any way you'd like.
function donators() {
var jsonURL = "http://mywebsite.com/donators.json";
var xhr = new XMLHttpRequest();
xhr.open("GET", jsonURL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
localDataStore.set("fb_donators", xhr.responseText);
}
};
xhr.timeout = 5000;
xhr.ontimeout = function() {
alert( 'The operation timed out.' );
}
try { xhr.send(); } catch( err ) {
alert( 'Error getting data: ' + err.message );
}
}

Categories