jQuery $.ajax error handling

19,276

First, congratulations on actually checking for errors. So many people write code that never expect things to go wrong on the internets. Ha.

Rather than editing every call to $.ajax you can call $.ajaxSetup() to have every call use your function for an error handler. The error handler signature is error(jqXHR, textStatus, errorThrown) which conveniently matches your function, so try a call to $.ajaxSetup({ error: logAjaxError }) before you do any $.ajax calls.

Share:
19,276
MB34
Author by

MB34

Updated on June 09, 2022

Comments

  • MB34
    MB34 almost 2 years

    Possible Duplicate:
    jQuery ajax error function

    I am trying to replace a "global" ajax error handler with a function that I can call from each ajax call due to problems observed in our implementation.

    $(document).ajaxError(function(e, jqXHR, settings, exception) {
        // using BrowserDetect function to get browser info
        var browser    = BrowserDetect.browser;
        var browserVer = BrowserDetect.version;
        var browserOS  = BrowserDetect.OS;
        var ajax_url   = settings.url;
        $.ajax({async: true, 
                type:     'POST',
                url:      AJAX_ERROR_LOG_URL, 
                dataType: 'json',
                data:     'host='myhost.com&status='+jqXHR.status+'&error='+jqXHR.responseText+'&expmessage='+exception.message+'&url=' 
                           +ajax_url+'&browser='+browser+'&browserVer='+browserVer+'&browserOS='+browserOS
        });
        if (jqXHR.status === 0) {
            final_message(ERROR_MSG + '0'); // Not connected. Please verify network is connected.
        } else if (jqXHR.status == 404) {
            final_message(ERROR_MSG + '404'); // Requested page not found. [404]
        } else if (jqXHR.status == 500) {
            final_message(ERROR_MSG + '500'); // Internal Server Error [500].
        } else if (exception === 'parsererror') {
            final_message(ERROR_MSG + '1'); // Requested JSON parse failed.
        } else if (exception === 'timeout') {
            final_message(ERROR_MSG + '2'); // Time out error.
        } else if (exception === 'abort') {
            final_message(ERROR_MSG + '3'); // Ajax request aborted.
        } else {
          if(browserVer == '7' && browser == 'Explorer') {
            final_message(ERROR_MSG + '100'); // Uncaught Error
          } else {
            final_message(ERROR_MSG + '99'); // Uncaught Error
          }
        }
    });
    

    I want to convert this to a function and call it like this:

    $.ajax({async: true, 
            type:'POST',
            url: url, 
            dataType: 'json', 
            data:     "username="+username+"&password="+pass,
            success:  ajaxLoginResult
            error:    logAjaxError(jqXHR, textStatus, errorThrown)
    });
    
    function logAjaxError(jqXHR, textStatus, errorThrown) {
      // more code here to log the error
    }
    

    The problem lies in the fact that I cannot get the url of the ajax callpassed to the error callback as the only things that are passed is the jqXHR, textStatus, errorThrown. In the .ajaxError setup, the settings is passed and that is where we get the url from. Any ideas?

    Edited 2/3: Here is the Add_Course function for you to see:

    function Add_Course(reason) {
      var eventid = $('#eventid'+$('#obleventcode').attr('value')).val();
      var url = AJAX_URL_ADDTOCART + '?sku='+eventid+'&mainitem=true&pid='+pid;
      if(reason != 'VOUCHER'){
        log_url(url);
        $.ajax({async: true, 
                type:'POST',
                url: url, 
                dataType: 'json', 
                success: function(data){
                  if(data.result=='success') {
                    var cemsg_index=reason.indexOf('CEMSG');
                    if(cemsg_index>=0) {
                      final_ce_message(reason.substr(cemsg_index+6));
                    } // if(cemsg_index>=0)
                  } else {
                    $('#sm_content .oblcontent').html(data.message);
                  } // if(data.result=='success')
                },
                complete: function(jqXHR, textStatus) {
                  log_url('redirecting to cart');
                  window.location = CART_URL;
                } // complete
        });
      }
    }