jQuery ajax generic error handling and on a case-b

2019-02-02 14:02发布

I have a generic ajax Error handler written like so:

$('html').ajaxError(function(e, xhr, settings, exception) {

    var message = '';

    if (xhr.status == 0) {
        message = 'You are offline!\n Please check your network.';
    }
    else if (xhr.status == 403) {
        window.location.href = $('#logon').attr('href');
    }
    else if (xhr.status == 404) {
        message = 'Requested URL not found.';
    }
    else if (xhr.status == 500) {

        message = xhr.responseText;

        $('#cboxLoadedContent div.news_article_content').append('<p>' + message + '</p>');

        try {//Error handling for POST calls
            message = JSON.parse(xhr.responseText);
        }

        catch (ex) {//Error handling for GET calls
            message = xhr.responseText;
        }

    }
    else if (errStatus == 'parsererror') {
        message = 'Error.\nParsing JSON Request failed.';

    }
    else if (errStatus == 'timeout') {
        message = 'Request timed out.\nPlease try later';
    }
    else {
        message = ('Unknown Error.\n' + xhr.responseText);
    }

    if (message != '' && xhr.status != 500) {
        message = message;
    }

    if (xhr.status != 403) {

        $('#icis_dashboard').append('<p id="ajax_error_msg" class="offScreen">' + message + '</p>');

        errorBox({
            inline: true,
            width: 0,
            href: '#ajax_error_msg',
            onLoadCall: function() { $('#cboxLoadedContent').jScrollPaneRemove(); },
            onCleanupCall: function() { $('#ajax_error_msg').remove(); }
        });
    }

});

So when the error is not 403 a dialog is shown with text relating to the error.

This is fine but what iwould like to do is have the generic handler as a backup and then deal with each error on an individual basis within the original ajax call.

so as the backup handler alerts "bar" on a 404 i would like to alert "foo" instead:

            error: function(xhr) {
            if (xhr.status == 404) {
                //window.location.href = $('#logon').attr('href');
                alert("foo");    
            }
        }

I sthere anyway to do this? I don't know how to prevent the backup from firing as they both seem to trigger at the moment.

7条回答
叼着烟拽天下
2楼-- · 2019-02-02 14:49

Define global error handler as function

function ajaxError() {
  var message = '';

  if (xhr.status == 0) {
    message = 'You are offline!\n Please check your network.';
  }
  .....
}

And create jQuery.ajax wrapper:

function doAjax(url, fnError) {
  jQuery.ajax(url, {
    error: fnError || defaultErrorHandler 
  })
}

Now use this wrapper instead default jQuery.ajax:

doAjax('/someResource'); // defaultErrorHandler using for handle error
doAjax('/someResource', function() {...}); // custom error function using
查看更多
登录 后发表回答