1

I am a new programmer whose primary background is in Java. I am attempting to write in fault handling to a program in Javascript as I would in Java. In java I use the Apache HTTP client to both create the client and call the Httpget request.

 HttpClient cli = new DefaultHttpClient();
 cli.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
 HttpResponse resp = null;
 for (int i = 0 ; i < 5 ; i++) {
 try {
 resp = cli.execute(new HttpGet("http://example.org/products"));
 }
 catch{//code}
 }

I am unsure how to emulate this behavior in a javascript environment. Does anyone have insight or knowledge into this field?

bluish
  • 26,356
  • 27
  • 122
  • 180
Bggreen
  • 123
  • 4
  • 10
  • 2
    That pattern is a bit distressing. Your fault tolerance is to try/catch the same request five times no matter what happens? – zetlen Jul 03 '12 at 17:50
  • SO you wanted HTTP GET request from javascript ? – Suave Nti Jul 03 '12 at 17:52
  • To zetlen, this is a piece of code from an easy example of "retry," where if you are having network issues, try again multiple times at intervals to see if the network has reconnected. To user104, yes the final goal is to emulate the HTTPget, but I didn't think you could do it without an instance of a client. Am i incorrect? – Bggreen Jul 03 '12 at 17:58
  • @Bggreen Is it common to retry without checking if the request was successful? – zetlen Jul 03 '12 at 18:01
  • 1
    I apologize, the code I posted is only a snipet from the whole. I'm sorry for the misunderstanding. Later in my loop I check if it did not error and break out if it did – Bggreen Jul 03 '12 at 18:05
  • @Bggreen I'm sorry, I think I didn't read your question carefully--you said you were a new programmer and I'm criticizing aspects of your work you didn't ask about. You are asking about what "class" to instantiate instead of DefaultHttpClient aren't you? – zetlen Jul 03 '12 at 18:07
  • @zetlen Yes, I'm looking for the functionality provided by creation of the Apache client and get request. From what I understand it is not available in JS – Bggreen Jul 03 '12 at 18:11

2 Answers2

1

In javascript, as in some other languages, "exception" handling is mostly replaced by error checking. For example you'll check the status of your xmlhttprequest object when issuing a request :

httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
                // ok, no "exception"
            } else {
                // BOOM ! "exception"
            }
        }
    }
}

Exceptions are only useful in a few places, like parseInt.

But I'm not sure that a heavy "fault tolerant" javascript code makes a lot of sense :

  • you really don't know where and how your code will be executed
  • all the important checks and all important persistence is client side

Your global system must be though with the idea that the browser is a foreign domain : nothing entering your server can be trusted.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thanks for the quick response! I understand the concern about the design, but I believe my final product will be sound. My issue is dealing with the request. I looked into the xmlhttprequest you mentioned and I believe it is the solution. Is there a "javadoc" for this object? On most pages I pull up I cannot tell the difference between the variables they are using and a built in function. I guess I'm spoiled from all the amazing documentation for Java. – Bggreen Jul 03 '12 at 18:22
  • There's nothing as simple and homogeneous as the javadoc, but you can try google and [MDN](https://developer.mozilla.org/fr/). Most of the times, you'll understand very fast the examples as a good javascript is much much much less verbose than a common java program. Just be sure to understand the basis (closures, scope, and so on) as presented [here](http://ejohn.org/apps/learn/) and you'll see that javascript is easy to grasp. – Denys Séguret Jul 03 '12 at 18:25
  • An alternative, for most uses, to the XmlHttpRequest, illustrating very well the event/callback logic of javascript is the [jquery ajax function](http://api.jquery.com/jQuery.ajax/) : you pass to this functions callbacks that will be called in case of success or failure. – Denys Séguret Jul 03 '12 at 18:29
  • This is exactly what I need, thanks. Id give you an upvote but apparently I'm too new here. – Bggreen Jul 03 '12 at 18:32
0

Here's the exact equivalent of your code snippet, but in JavaScript!

 var cli;
 var callback = function(resp) {
    // due to the asynchronous nature of XMLHttpRequest, you'll need to put all logic that uses the response in a callback function.
    // code below using responseText
    console.log(resp);
 };
 var timeout = 5000;
 var handler = function() {
    var errorSeries;
    if (this.readyState === 4) { // indicates complete
        errorSeries = parseInt(this.status.toString().charAt(0)); // will be "2" or "3" for 200 or 300 series responses
        if (errorSeries === 2 || errorSeries === 3) {
            callback.call(this, this.responseText);
        } else {
            // handle http error here
        }
    }
 }
 for (var i = 0 ; i < 5 ; i++) {
 cli = new XMLHttpRequest(); // ActiveXObject('Microsoft.XMLHTTP') in IE8 and below
 cli.timeout = timeout;
 cli.onreadystatechange = handler;
 try {
    cli.open('GET','http://example.org/products');
    cli.send();
 }
 catch(e) {
 }

If the above looks wordy, that's because it is. Other commenters have steered you right: look into using a library like jQuery to abstract away this kind of boilerplate.

deadboy
  • 849
  • 2
  • 9
  • 28
zetlen
  • 3,609
  • 25
  • 22