<p>When using <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a>'s <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="nofollow noreferrer">ajax method</a> to submit form data, what is the best way to handle errors?
This is an example of what a call might look like:</p>

<pre><code>$.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();
        }
});
</code></pre>

<p>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.</p>

<p>My problem seems to be that by throwing an exception the ashx causes the <code>statusText</code> and <code>errorThrown</code> to be <strong>undefined</strong>.</p>

<p>I can get to the <code>XMLHttpRequest.responseText</code> which contains the HTML that makes up the standard .net error page.</p>

<p>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.</p>

<p>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 <code>userCreation.ashx</code>, then using this to decide what action to take?<br>
How do you handle these situations?</p>

[{'answer_id': 28537, 'author': 'Ian Robinson', 'author_id': 326, 'author_profile': 'https://Stackoverflow.com/users/326', 'pm_score': 5, 'selected': True, 'text': '<blockquote>\n  <p>Should I be throwing the errors in the\n  ashx, or should I be returning a\n  status code as part of the data\n  returned by the call to\n  userCreation.ashx, then using this to\n  decide what action to take? How do you\n  handle these situations?</p>\n</blockquote>\n\n<p>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).</p>\n\n<p>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.</p>\n'}, {'answer_id': 28545, 'author': 'travis', 'author_id': 1414, 'author_profile': 'https://Stackoverflow.com/users/1414', 'pm_score': 4, 'selected': False, 'text': '<p>For debugging, I usually just create an element (in the case below: <code>&lt;div id="error"&gt;&lt;/div&gt;</code>) on the page and write the XmlHttpRequest to it:</p>\n\n<pre><code>error: function (XMLHttpRequest, textStatus, errorThrown) {\n    $("#error").html(XMLHttpRequest.status + "\\n&lt;hr /&gt;" + XMLHttpRequest.responseText);\n}\n</code></pre>\n\n<p>Then you can see the types of errors that are occurring and capture them correctly:</p>\n\n<pre><code>if (XMLHttpRequest.status === 404) // display some page not found error\nif (XMLHttpRequest.status === 500) // display some server error\n</code></pre>\n\n<p>In your ashx, can you throw a new exception (e.g "Invalid User" etc.) and then just parse that out of the <code>XMLHttpRequest.responseText</code>? For me when I get an error the <code>XMLHttpRequest.responseText</code> isn\'t the standard Asp.Net error page, it\'s a JSON object containing the error like this:</p>\n\n<pre><code>{\n"Message":"Index was out of range. Must be non-negative and less than the size of the collection.\\r\\n\nParameter name: index",\n"StackTrace":" at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)\\r\\n \nat etc...",\n"ExceptionType":"System.ArgumentOutOfRangeException"\n}\n</code></pre>\n\n<p>Edit: This could be because the function I\'m calling is marked with these attributes:</p>\n\n<pre><code>&lt;WebMethod()&gt; _\n&lt;ScriptMethod()&gt; _\n</code></pre>\n'}, {'answer_id': 29915, 'author': 'AidenMontgomery', 'author_id': 1403, 'author_profile': 'https://Stackoverflow.com/users/1403', 'pm_score': 2, 'selected': False, 'text': '<p>Now I have a problem as to which answer to accept.</p>\n\n<p>Further thought on the problem brings me to the conclusion that I was incorrectly throwing exceptions. Duplicate user names, email addresses etc are expected issues during a sign up process and are therefore not exceptions, but simply errors. In which case I probably shouldn\'t be throwing exceptions, but returning error codes.</p>\n\n<p>Which leads me to think that <a href="https://stackoverflow.com/users/326/irobinson">irobinson\'s</a> approach should be the one to take in this case, especially since the form is only a small part of the UI being displayed. I have now implemented this solution and I am returning xml containing a status and an optional message that is to be displayed. I can then use jQuery to parse it and take the appropriate action: -</p>\n\n<pre><code>success: function(data){\n    var created = $("result", data).attr("success");\n    if (created == "OK"){\n        resetNewUserForm();\n        listUsers(\'\');\n    } else {\n        var errorMessage = $("result", data).attr("message");\n        $("#newUserErrorMessage").text(errorMessage).show();\n    }\n    enableNewUserForm();\n}\n</code></pre>\n\n<p>However <a href="https://stackoverflow.com/users/1414/travis">travis\'</a> answer is very detailed and would be perfect during debugging or if I wanted to display an exception message to the user. I am definitely not receiving JSON back, so it is probably down to one of those attributes that travis has listed, as I don\'t have them in my code.</p>\n\n<p>(I am going to accept irobinson\'s answer, but upvote travis\' answer. It just feels strange to be accepting an answer that doesn\'t have the most votes.)</p>\n'}]
['https://Stackoverflow.com/questions/28529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1403/']