I have some jQuery that makes a call into a WCF service. When the service runs into an error, it throws a WebFaultException
with a description and a 500 Internal Server Error
status code.
Client side, I'm doing something along the lines of:
$.ajax({
url: BaseUrl + 'ThisShouldThrowAnException',
type: 'GET',
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
// this should never be called
alert("Got data: " + data);
},
error: function (jqXHR, status, message) { // never called
// would like this to handle my status code
alert(status + " " + message);
}
});
On the local IIS server, the corresponding code that's being invoked is given as:
[OperationContract]
[WebGet(RequestFormat=WebMessageFormat.Json)]
bool ThisShouldThrowAnException();
public bool ThisShouldThrowAnException()
{
throw new WebFaultException<String>("Something really bad happened.", HttpStatusCode.InternalServerError);
}
The issue is that when I make this call, the success function is called. jQuery seems to swallow my 500 Internal Server Error
and instead gives me a 200 OK
. Inspection using Fiddler also reveals that my response status code is a 200 OK
. When I call via the browser or if I handcraft a request I receive the appropriate 500 Internal Server Error
.
My question is: How can I handle a WebExceptionFault
inside of a $.ajax(...)
call? As it stands, the $.ajax
is completely ignoring any status code that gets passed to it.
I tried using ajaxError
and statusCode
, but neither worked:
$('#error').ajaxError(function() {
alert("An error occurred");
});
$.ajax({
url: BaseUrl + 'ThisShouldThrowAnException',
type: 'GET',
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
alert("Got data: " + data);
},
statusCode: {
500: function() {
alert("Got 500 Internal Server Error");
}
},
error: function (jqXHR, status, message) {
alert(status + " " + message);
}
});
New Findings
On further analysis, when I inspected the query string that jQuery generates I find that the following returns a 200 OK
:
http://localhost/RestService/RestService.svc/ThisShouldThrowAnException?callback=jQuery172003801283869839445_1341495740773&_=1341495740777
// on page:
jQuery172003801283869839445_1341495740773("Something really bad happened.",500);
Meanwhile, the following request returns a 500 Internal Server Error
:
http://localhost/RestService/RestService.svc/ThisShouldThrowAnException
// on page:
"Something really bad happened"