jquery ajax ignores 500 status error
Asked Answered
C

3

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.

Corporeity answered 24/3, 2011 at 14:8 Comment(1)
Shouldn't it be statusCode instead of status?Parochialism
C
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.');
            }
        }
    });
});
Caryl answered 24/3, 2011 at 14:17 Comment(5)
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.Corporeity
I don't see anything else wrong with your code - the error callback should work as written. Could you post an SSCCE?Caryl
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 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.Corporeity
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?).Caryl
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.Corporeity
G
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)

Givens answered 25/8, 2014 at 18:44 Comment(0)
P
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>');
                    });
Panek answered 29/9, 2014 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.