AidenMontgomery AidenMontgomery - 16 days ago 5
jQuery Question

How would you 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?

Answer

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?

Personally, if possible, I would prefer to handle this on the server side and work up a message to the user there. This works very well in a scenario where you only want to display a message to the user telling them what happened (validation message, essentially).

However, if you want to perform an action based on what happened on the server, you may want to use a status code and write some javascript to perform various actions based on that status code.