I'm trying to add a global error handler, and first test was with a call where I purposefully caused error code 401 due to no Access-Control-Allow-Origin
header.
I've used Chrome to show the error and verify that it is thrown but I can't figure out how to use the handler to display that message.
The jqxhr.status
is 0
and jqxhr.statusText
is "error"
and the thrownError
is an empty string.
Using Chrome, I couldn't find the code and message in any of the function variables. Is there a way to show the code and message seen in Chrome debug mode?
$(document).ajaxError(function (event, jqxhr, settings, thrownError) {
alert("Global Error Catch. Error of " + thrownError + " at url = " + settings.url + " event type of " + settings.type
+ " with event data of " + event.data + " and event type of " + event.type + " and event target of " + event.target
+ " and the jqXHR.status is " + jqxhr.status + " and jqXHR.statusText is " + jqxhr.statusText
+ " and the jqXHR.responseText is " + jqxhr.responseText + " and jqXHR.responseXML is " + jqxhr.responseXML);
});
Looking at the code again I noticed that the button click event uses jQuery.when()
to find some input variable values before finally making the ajax call that triggers the 401. Could that be why ajaxError
is not showing the error in thrownError
?
Update
After further testing this is not related to the jQuery.when()
. But could this be related to the fact I'm making a cross domain ajax request?
Fiddler can at least see a 401 unauthorized
response and when using Chrome debug mode I can see both the 401 unauthorized
and the Access-Control-Allow-Origin
error message. But is that only sent back to the calling code if I do it myself in the web api? I assumed since it was visible in both Fiddler and Chrome it should be somewhere visible to the global ajaxError
handler.
Update2 After more testing this does be related to the nature of a CORS request and not how I've used the global error catching. I might need to create a separate question on that specific topic.
I have also tried the code below and jqXHR.status
returns 0 and textStatus = "error"
and errorThrown=""
. I think this is similar to the question posted here on status code 0 for a 401 in fiddler but I don't see a solution posted. I will searching for posts similar to that and if I find one I will include it as an answer.
$.ajaxSetup({
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 401) {
alert("Error 401 : " + textStatus + ": " + errorThrown);
} else {
alert("Error: " + textStatus + ": " + errorThrown);
}
}
});