I have a website where an ajax call will get some Json data from a Asp.Net-Mvc action.
Now I’m trying to do implant errorhandling in it.
But I’m stuck at the point how to do it.
The easyst way i found, was cattch the exceptions in the controller action, and Return a Json object with an error message in. And then in the ajax succes function, I can output the error message if its excist.
But I’m not sure that’s the best way, so i tried to use the error function of the ajax call.
my code is something like this:
$.ajax(
{
type: "POST",
url: "/home/geterror",
data: "",
dataType: "json",
success: function(result)
{
//do something
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert(XMLHttpRequest.responseText + " "+ XMLHttpRequest.status +" "+ textStatus +" "+ errorThrown);
}
});
I saw that the XMLHttpRequest.responseText is a standard asp.net error page with my errormessage in the title. the errorThrown is allways undefined.
Now I’m trying to get the title out of the XMLHttpRequest.responseText. But I dont know how to do that. (everything i tried failed ..)
So if anyone has any sugestion, or better way’s to handle errors with Ajax-calls…
Thanks,
Bruno
Bruno, I think you should make a distinction here; you have custom or expected errors you want to show to the users, like an invalid value provided where you have to tell the user “sir, you can not do this because bla bla” and on the other hand you have other unexpected errors like for example a bug in your code which causes some unwanted exception like for example a violation of a FK in an insert. My suggestion is to handle globally the latter ones, you can setup query ajax requests to have some common behavior, with for example ajaxSetup. In that way you setup a common error handler (status 500). In the case you have an “expected” error (the first case in my example) you should return a special object as Darin showed in his answer and handle it in the success callback, after all, this is a valid scenario and you should handle it as such.