bruno
bruno

Reputation: 1841

error handling in an ajaxcall

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

Upvotes: 0

Views: 1307

Answers (3)

uvita
uvita

Reputation: 4124

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.

Upvotes: 3

Anurag
Anurag

Reputation: 141929

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);
    });
});

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

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');

Upvotes: 2

Related Questions