views:

82

answers:

3

Hi all,

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

+1  A: 
public ActionResult Index()
{
    try
    {
        // Do something
        return Json(new { status = true, errorMessage = "" });
    }
    catch (SomeSpecialExceptionYouWantToHandle e)
    {
        return Json(new { status = false, errorMessage = e.Message });
    }
}

And the ajax call:

$.post('/home/index', { }, function(result) {
    if (result.status) {
        alert('success');
    } else {
        alert(result.errorMessage);
    }
}, 'json');
Darin Dimitrov
That was my first solution, but my colleague didnt find that a 'good solution' so i should look after an other solution. But thx!
bruno
+2  A: 

It's much better to handle error processing inside the error callback. For jQuery to detect it as an error, you need to set the HTTP response code to some 4xx or 5xx. I don't know ASP.NET so bear with me, but you need something to this effect.

Response.code = '401'
Response.text = JSON({ message: 'An error occurred.', ... })

On the client side, parse the JSON response.

$.ajax({
    ...
    error: function(request, status, error) {
        var result = JSON.parse(request.responseText);
        alert(result.message);
    });
});
Anurag
Thx, I was first looking at a solution like this but i didn't find a way to set the response code. But i found it now. And it works with this solution.
bruno
glad it worked for you!
Anurag
+1  A: 

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.

uvita
an expected error is still an error. network related or application related does not make the operation successful, and it should be dealt as such.
Anurag
Anurag, maybe I didn´t express myself well, what I mean is that you usually have alternative flows in which you have to tell the user that something has happened. Imagine for example a user that forgot his password and wants to reset his password, providing his email. If he types an incorrect email (one that doesn´t exist for example), then you have to handle that case as an expected situation and take care of it in the succcess callback. Differente is the case when you have an unexpected NullReferenceException or any other unexpected error.
uvita
I got the point that you were referring to alternate flows in your answer, but you could classify those as errors (or exceptions) too. I think of it as an error because the intended action (sending an email out) was not performed due to whatever reasons. If it is handled as such, every success callback will not be littered with `if(result.wasSuccessful) { .. } else { .. }`, but rather the error callback will take over and depending on the returned code, an appropriate action will be taken.
Anurag
Hey, thx for the answer! I was already handling 'wrong mail'- errors in my success handler. I was searching at a good solution to catch the real trown exceptions in the error handler of my ajax call. The ajaxsetup is really great for this too.
bruno