How to Use jQuery ajaxError to Log Errors Globally

The jQuery .ajaxError() method provides a centralized way to capture and handle HTTP request failures across an entire application. Rather than attaching error callbacks to every individual $.ajax, $.get, or $.post call, you can register a single global listener on the document object. This guide demonstrates how to configure .ajaxError(), inspect the error payload, and log critical failure details to the console or an external monitoring service.

Understanding the .ajaxError() Syntax

To intercept failed AJAX requests globally, attach .ajaxError() directly to $(document). The handler receives four key arguments whenever a request fails:

$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    // Error handling logic goes here
});
  • event: The jQuery event object representing the error event.
  • jqXHR: The jQuery XMLHttpRequest object containing server response details, including status, statusText, and responseText.
  • ajaxSettings: The settings configuration object used for the request, such as url, type (HTTP method), and serialized data.
  • thrownError: The JavaScript exception object or HTTP status text (e.g., "Internal Server Error", "Timeout", "Not Found").

Basic Global Logging Implementation

The following example captures any failed AJAX request, extracts contextual information about the failure, and formats it for debugging:

$(document).ready(function() {
    $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
        const errorDetails = {
            url: ajaxSettings.url,
            method: ajaxSettings.type,
            status: jqXHR.status,
            statusText: jqXHR.statusText,
            response: jqXHR.responseText,
            error: thrownError,
            timestamp: new Date().toISOString()
        };

        console.error("Global AJAX Failure Detected:", errorDetails);
    });
});

Filtering Errors by HTTP Status

Not all failed responses require the same logging behavior. You can filter logs by inspecting jqXHR.status:

$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    if (jqXHR.status === 401) {
        // Handle session expiration or unauthorized access
        console.warn("Unauthorized request to:", ajaxSettings.url);
    } else if (jqXHR.status >= 500) {
        // Log critical server crashes
        console.error("Server 5xx error at:", ajaxSettings.url, jqXHR.responseText);
    } else if (thrownError === "timeout") {
        console.error("Request timed out:", ajaxSettings.url);
    }
});

Sending Errors to a Remote Logging Endpoint

When transmitting failure reports back to your server or a third-party error-tracking endpoint, prevent infinite loops by using the native Fetch API, navigator.sendBeacon(), or setting global: false on the reporting AJAX request.

$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    // Avoid capturing errors from the logging service itself
    if (ajaxSettings.url === "/api/log-client-error") {
        return;
    }

    const payload = JSON.stringify({
        endpoint: ajaxSettings.url,
        statusCode: jqXHR.status,
        message: thrownError || jqXHR.statusText,
        userAgent: navigator.userAgent
    });

    // Use sendBeacon to transmit data reliably without triggering jQuery global events
    if (navigator.sendBeacon) {
        navigator.sendBeacon("/api/log-client-error", payload);
    } else {
        // Alternatively, use jQuery with global disabled
        $.ajax({
            url: "/api/log-client-error",
            type: "POST",
            contentType: "application/json",
            data: payload,
            global: false // Prevents this request from triggering .ajaxError()
        });
    }
});

Excluding Specific Requests from Global Error Logging

If a particular request handles its own errors or is expected to fail silently, disable global events by setting global: false within that specific call:

$.ajax({
    url: "/api/check-status",
    type: "GET",
    global: false, // Bypasses .ajaxError() entirely
    error: function(xhr, status, error) {
        // Local error handling only
    }
});