Aid*_*ery 33 asp.net ajax jquery
当使用jQuery的ajax方法提交表单数据时,处理错误的最佳方法是什么?这是一个调用可能的示例:
$.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();
}
});
Run Code Online (Sandbox Code Playgroud)
该请求可能由于多种原因而失败,例如重复的用户名,重复的电子邮件地址等,并且写入ashx以在发生这种情况时抛出异常.
我的问题似乎是,通过抛出异常的ashx的导致statusText
和errorThrown
被未定义.
我可以访问XMLHttpRequest.responseText
包含组成标准.net错误页面的HTML.
我在responseText中找到页面标题,并使用标题来确定抛出了哪个错误.虽然我怀疑当我启用自定义错误处理页面时这会崩溃.
我应该在ashx中抛出错误,还是应该返回状态代码作为调用返回的数据的一部分userCreation.ashx
,然后使用它来决定采取什么操作?
你如何处理这些情况?
tra*_*vis 20
对于调试,我通常只是<div id="error"></div>
在页面上创建一个元素(在下面的情况下:),并将XmlHttpRequest写入它:
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#error").html(XMLHttpRequest.status + "\n<hr />" + XMLHttpRequest.responseText);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以看到正在发生的错误类型并正确捕获它们:
if (XMLHttpRequest.status === 404) // display some page not found error
if (XMLHttpRequest.status === 500) // display some server error
Run Code Online (Sandbox Code Playgroud)
在你的ashx中,你可以抛出一个新的异常(例如"无效用户"等),然后只是解析出来的那个XMLHttpRequest.responseText
?对我来说,当我收到错误时,XMLHttpRequest.responseText
不是标准的Asp.Net错误页面,它是一个包含如下错误的JSON对象:
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
编辑:这可能是因为我正在调用的函数标有以下属性:
<WebMethod()> _
<ScriptMethod()> _
Run Code Online (Sandbox Code Playgroud)
Ian*_*son 16
我应该在ashx中抛出错误,还是应该返回状态代码作为调用userCreation.ashx返回的数据的一部分,然后使用它来决定采取什么操作?你如何处理这些情况?
就个人而言,如果可能的话,我宁愿在服务器端处理这个问题,并在那里向用户处理一条消息.这种情况非常适用于您只想向用户显示消息,告诉他们发生了什么(基本上是验证消息).
但是,如果要根据服务器上发生的操作执行操作,可能需要使用状态代码并编写一些javascript以根据该状态代码执行各种操作.