'Global ajaxError event before local error event

I have a global ajaxError event, something like this:

$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
    alert("There was a global ajax error!");
});

And I have many local ajaxEvents, something like this:

$(imageUploadForm).ajaxForm({
            url: assetsUplUrl,
            type: 'POST',
            dataType: 'json',
            data: {project_id: projectId, type: 'image', widget: widget},
            error: function(responseText, status, xhr, form){
                 alert("There was a local ajax error!");
            }
        });     

How can i get the global error event to trigger before the local one without changing in the local ajax?



Solution 1:[1]

The accepted answer did not work for me. According to https://api.jquery.com/jQuery.ajaxSetup, global callback functions should be set with their respective global Ajax event handler methods rather than within the options object for $.ajaxSetup().

My solution was to use $.ajaxPrefilter like this:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    let error = options.error;
    options.error = function (jqXHR, textStatus, errorThrown) {
        // global error handling first
        console.log('global ajax error');
        
        // override local error handling if exists
        if ($.isFunction(error)) {
            return $.proxy(error, this)(jqXHR, textStatus, errorThrown);
        }
    };
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ge333