Explicitly send XHR errors for unhandled AJAX errors


Posted on
Mar 10 2016

I'm using Raygun JS client and making jQuery ajax REST API requests.

The API will, by design, return 404 Not Found if the requested resource is not found. This is creating unnecessary entries in Raygun because the requests are being made due to user input. e.g. look up membership number. This is just one example.

To get around this I have set the raygun init setting ignoreAjaxError:true but what I am lacking is an elegant solution for explicitly logging unexpected ajax errors.

error: function (xhr, statusText, err) {
    if (xhr.status === 404) {
        // This is expected
    } else {
        // This is not
        sendRaygunAjaxError(event, xhr, err);

This is what I have come up with so far:

Added the following to every ajax call setup to hack a copy of the ajax call settings into the xhr object:

beforeSend: function (xhr, settings) {
    xhr.raygunData = settings;

Created a helper function to do the dirty work:

var sendRaygunAjaxError = function (event, xhr)
    try {
        throw new Error("AJAX Error: " + xhr.statusText + " " + xhr.raygunData.type + " " + xhr.raygunData.url);
    } catch (e) {
        Raygun.send(e, {
            status: xhr.status,
            statusText: xhr.statusText,
            type: xhr.raygunData.type,
            url: xhr.raygunData.url,
            contentType: xhr.raygunData.contentType,
            requestData: xhr.raygunData.data && xhr.raygunData.data.slice ? xhr.raygunData.data.slice(0, 10240) : undefined,
            responseData: xhr.responseText && xhr.responseText.slice ? xhr.responseText.slice(0, 10240) : undefined

Please tell me that there's a better way! Is there a way of using the processJQueryAjaxError function that I can see in the Raygun code?

I also don't like turning on the ignoreAjaxError setting globally because I may miss errors in other places. Is there a way of turning it on per ajax call setup?


Posted on
Mar 10 2016

Hi cb,

You could create a onBeforeSend handler which inspects the Details.UserCustomData.status field of the payload of AJAX errors and returns false if the status is 404.

The handler should look something like this:

Raygun.onBeforeSend(function(payload) {
    if(payload.Details.Error.Message.includes('AJAX Error')) {
        if(payload.Details.UserCustomData.status === 404) {
            return false;
    return payload;

Give that a shot and let us know how you get on.

Best regards,


Posted on
Mar 10 2016

Thanks Alex. I didn't realise that you could cancel the error in onBeforeSend.

I'll give it a shot. This looks like a much better approach.