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

For debugging, I usually just create an element (in the case below: <div id="error"></div>) on the page and write the XmlHttpRequest to it:

error: function (XMLHttpRequest, textStatus, errorThrown) {
    $("#error").html(XMLHttpRequest.status + "\n<hr />" + XMLHttpRequest.responseText);
}

Then you can see the types of errors that are occurring and capture them correctly:

if (XMLHttpRequest.status === 404) // display some page not found error
if (XMLHttpRequest.status === 500) // display some server error

In your ashx, can you throw a new exception (e.g “Invalid User” etc.) and then just parse that out of the XMLHttpRequest.responseText? For me when I get an error the XMLHttpRequest.responseText isn’t the standard Asp.Net error page, it’s a JSON object containing the error like this:

{
"Message":"Index was out of range. Must be non-negative and less than the size of the collection.\r\n
Parameter name: index",
"StackTrace":" at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)\r\n 
at etc...",
"ExceptionType":"System.ArgumentOutOfRangeException"
}

Edit: This could be because the function I’m calling is marked with these attributes:

<WebMethod()> _
<ScriptMethod()> _

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)