14

I'm making some GET requests to an App Engine app, testing in Chrome. Whilst I can see in javascript console that some calls result in a 500 server error, I can't seem to find anyway of capturing this error in my jQuery code despite reading a number of similar SO threads. I understand that it indicates a server side error, but I'd still like to be able to capture such an error from my javascript.

I need to capture the error so that I can count the number of responses (successful or otherwise) and trigger another function when all call responses have been received.

Chrome console output:

GET http://myapp.com/api?callback=jQuery12345&params=restOfParams 500 (Internal Server Error)

My call:

  function makeCall() {
    var count = 0;
    var alldata = $('#inputset').val();
    var rows = alldata.split('\n');
    var countmatch = rows.length;
    for (i=0;i<rows.length;i++) {
      data["param"] = rows[i]["val"];
      $.ajax({
              url: apiUrl,
              type: 'GET',
              data: data,
              dataType: 'jsonp',
              error: function(){
                  alert('Error loading document');
                  count +=1;
              },
              success: function(responseJson) {
                            count +=1;
                            var res = responseJson.results;
                            if (count == countmatch) {
                              allDoneCallback(res);
                            }
                        },
             });
    }
}

I've tried some of the following:
Adding:

statusCode: {500: function() {alert('err');}}

to the call.

Using:

  $().ready(function(){
     $.ajaxSetup({
       error:function(x,e) {
             if(x.status==500) {
               alert('Internel Server Error.');
             }
           }
      });
   });

Would anyone have a suggestion regarding how I could catch the 500 response?

Thanks Oli

UPDATE:

Based on responses, my jquery code appears to be correct, but for some reason it would only catch certain 500 responses received from my app. This is possibly a problem with how App Engine returns the error(I don't know a lot about this), or how jquery handles errors with jsonp - this point is briefly discussed in the last paragraph of this article.

I got this to work by using jquery-isonp which caught all of the 500 status's thrown by the app.

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
oli
  • 3,541
  • 1
  • 27
  • 34

3 Answers3

4

It doesn't look like you're using jQuery's document.ready binding correctly. The $().ready(...) version is more-or-less deprecated. Try one of these instead:

$(document).ready(function() {
    $.ajaxSetup({
        error: function(x, e) {
            if (x.status == 500) {
                alert('Internel Server Error.');
            }
        }
    });
});

or the shorthand:

$(function() {
    $.ajaxSetup({
        error: function(x, e) {
            if (x.status == 500) {
                alert('Internel Server Error.');
            }
        }
    });
});
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Hi Matt, Thanks for getting back to me. I tried both of those suggestions but still no luck unfortunately.. it's odd, I wonder if chrome console is recognising the 500 status, but jquery is not for some reason? I'm in Chrome 10.0.648.151, using jquery 1.5.1. I will test this in FF now. – oli Mar 24 '11 at 14:29
  • I don't see anything else wrong with your code - the `error` callback should work as written. Could you post an [SSCCE](http://sscce.org/)? – Matt Ball Mar 24 '11 at 14:31
  • Hi Matt, unfortunately I can't right now (the app I'm calling is housed internally to a company); however, I think I've managed to isolate the issue slightly further: The [App Engine](http://code.google.com/appengine/docs/python/tools/webapp/redirects.html) app returns the 500 when it hits an error internally (jquery does not detect this); if I use it's self.error(500) functionality, the jquery DOES detect it. As far as I can see in the browser both come back as pretty much the same thing, so I still don't get why one is correctly identified. – oli Mar 24 '11 at 17:34
  • What do you mean by "the app returns the 500?" It sounds like the GAE app isn't sending the right HTTP status code unless you use the `self.error(500)` (so, why not just do that?). – Matt Ball Mar 24 '11 at 17:45
  • Hi Matt, apologies if my description didn't make complete sense. When GAE throws certain errors (I believe a DeadlineExceededError is a suitable example - requests takes longer than 30 seconds to process) it appears to throw a 500 error. This is what my browser sees anyway. I'm not sure what is different between this error and the 500 it throws, and the self.error(500), the only difference is I force the second one myself.. I don't want to waste your time so I think I'll dig into fixing this on my app, but ultimately I don't see why jquery treats these two responses differently. – oli Mar 25 '11 at 09:54
1

Solved the problem by upgrading jQuery from 1.9.1 to 2.1.1 — now it started calling .error() right on the server response (before it would ignore the 500 response and wait until timeout is over).

Limitation: jQuery 2.1.1 does not support IE8 and below (as IMO shouldn't you)

Angie
  • 1,475
  • 1
  • 10
  • 5
1

I had a similar problem, I was using jquery's promise functions of .done, .fail, .always, and if I encountered a 500 internal server error then it would not fire any of the functions (done, fail, always, error). very weird.

in the end I added a timeout into the .ajax options, when it hits the timeout it throws an error and also runs the .fail method.

searchify.myAjaxSearchTerms = $.ajax({
                        'url': url,
                        type: "GET",
                        'dataType': 'jsonp',
                        'jsonp': 'json.wrf',
                        'jsonpCallback': searchify.cbFunc,
                        timeout: 4000, //needed for 500 errors - will go to fail block on timeout
                        beforeSend: searchify.beforeSendAutocomplete

                    });
searchify.myAjaxSearchTerms.fail(function(XHR, status, error){
                        searchify.clearForm();
                        searchify.renderWarningForNoQuery('<div class="notify-bubble"><span class="icon" data-icon="8" aria-hidden="true"></span><span>Sorry. We had a problem performing that search...<br/>Please try again<br/>Enter a <strong>product name</strong>, <strong>catalogue number</strong> or <strong>keyword</strong></span></div>');
                    });
J nui
  • 188
  • 1
  • 13