14

I have the following code for default jQuery AJAX error handling:

$.ajaxSetup({
    error : function(jqXHR, textStatus, errorThrown) {
        alert("Error: " + textStatus + ": " + errorThrown);
    },
    statusCode : {
        404: function() {
            alert("Element not found.");
        }
    }
});

However, when 404 happens, BOTH functions are upcalled: first error, then statusCode, so I see 2 consecutive alerts.

How to prevent this behaviour and get error callback only if statusCode was not upcalled?

2
  • 1
    No-no. I want a specific message in case of 404, and the default one otherwise. Commented Jan 18, 2012 at 18:40
  • 4
    I'm with you @weekens. The lack of an 'else' on statusCode entries, or absent that, some way to call your statusCode handler first and allow it to suppress the generic error handler if it wants to, makes the whole statusCode option useless IMO. It's only usable if you have statusCode entries for every possible error code, not reasonable. I hope the jQuery folks reconsider this architecture. Commented Nov 8, 2012 at 13:42

2 Answers 2

30

How about just checking for status code 404 in your error handler?

$.ajaxSetup({
    error : function(jqXHR, textStatus, errorThrown) {
        if (jqXHR.status == 404) {
            alert("Element not found.");
        } else {
            alert("Error: " + textStatus + ": " + errorThrown);
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

12

Try this:

$.ajaxSetup({
error : function(jqXHR, textStatus, errorThrown) {
    if(jqXHR.status === 404) {
      alert("Element not found.");
    } else {
      alert("Error: " + textStatus + ": " + errorThrown);
    }
}
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.