Maksud Mansuri
Maksud Mansuri

Reputation: 651

How would i handle errors when using jQuery.ajax()?

When using jQuery's AJAX method to submit form data, what is the best way to handle errors? This is an example of what a call might look like:

$.ajax({
    url: "userCreation.ashx",
    data: { u:userName, p:password, e:email },
    type: "POST",
    beforeSend: function(){disableSubmitButton();},
    complete: function(){enableSubmitButton();},
    error: function(xhr, statusText, errorThrown){
            // Work out what the error was and display the appropriate message
        },
    success: function(data){
            displayUserCreatedMessage();
            refreshUserList();
        }
});

The request might fail for a number of reasons, such as duplicate user name, duplicate email address etc, and the ashx is written to throw an exception when this happens.

My problem seems to be that by throwing an exception the ashx causes the statusText and errorThrown to be undefined. I can get to the XMLHttpRequest.responseText which contains the HTML that makes up the standard .net error page.

I am finding the page title in the responseText and using the title to work out which error was thrown. Although I have a suspicion that this will fall apart when I enable custom error handling pages.

Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to userCreation.ashx, then using this to decide what action to take? How do you handle these situations?

Upvotes: 0

Views: 854

Answers (2)

Alexis Wilke
Alexis Wilke

Reputation: 20725

If the server does not do something it was kindly asked to do, then it makes more sense for the server to return an error code along a message.

For example, trying to create a new user with an existing user name could return an error such as:

409 Conflict: User Exists

When the server returns an HTTP code other than 200 to 299, or 304 (i.e. not modified), then your error() callback gets called. The textStatus should be set to error in that case.

The HTTP error code can be checked looking at the status field as in:

if(jqxhr.status == 409)
{
    // got a conflict (i.e. same username)
    ...
}

And as you mentioned in your answer, the jqxhr.responseText will include the error message ("Conflict: User Exists" in my example above.)

Upvotes: 0

Mahesh
Mahesh

Reputation: 26

Make sure you're setting Response.StatusCode to something other than 200. Write your exception's message using Response.Write, then use...

xhr.responseText

in your javascript/ajax I hope this work.

Upvotes: 1

Related Questions