在ajax调用失败时,在vb.net中获取xhr对象

时间:2010-09-03 11:06:07

标签: web-services exception-handling jquery error-handling asmx

我在jQuery.ajax电话中遇到了一个大问题。我点击更新按钮时调用Web服务。我有一个单独的Web服务类,其中包含很少的方法。当我调用Web服务方法时,我已经进行了错误处理并在db中记录错误信息,之后我必须覆盖“ex”,这意味着错误对象为XMLHttpRequest。是否可以在SqlException中将xhr分配给ajax对象(VB.NET)?请帮助我对我更有用。

1 个答案:

答案 0 :(得分:0)

是的,这是可能的!我尝试在VB.NET中描述它(主要是我使用C#,但我希望我不会出现语法错误)。我们有一个Web服务

<WebMethod()> _
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function GetData(ByVal Age As Integer) As String
If Age <= 0 Then
    Throw(New ArgumentException("The parameter age must be positive."))
End If
'... some code
End Function

C#中的相同代码看起来像

[WebMethod]
[ScriptMethod (UseHttpGet=true)]
public string GetData(int age)
{
    if (age <= 0)
        throw new ArgumentException("The parameter age must be positive.");
    // some code
}

如果年龄输入为负,则会抛出异常ArgumentException(我解释的所有内容对于SqlException等其他异常保持不变。

现在您有一个使用jQuery.ajax来调用服务的JavaScript代码。然后,您可以通过以下方式扩展代码以支持异常处理:

$.ajax({
    type: "GET",
    url: "MyWebService.asmx/GetData",
    data: {age: -5},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data, textStatus, xhr) {
        // use the data
    },
    error: function(xhr, textStatus, ex) {
        var response = xhr.responseText;
        if (response.length > 11 && response.substr(0, 11) === '{"Message":' &&
            response.charAt(response.length-1) === '}') {

            var exInfo = JSON.parse(response);
            var text = "Message=" + exInfo.Message + "\r\n" +
                       "Exception: " + exInfo.ExceptionType;
                      // + exInfo.StackTrace;
            alert(text);
        } else {
            alert("error");
        }
    }
});

如果抛出异常,我们会收到有关JSON格式错误的信息。我们将其反序列化为具有MessageExceptionTypeStackTrace属性的对象,然后显示如下错误消息

Message: The parameter age must be positive.
Exception: System.ArgumentException

在实际应用程序中,您可能永远不会显示StackTrace属性的值。最重要的信息位于Message:例外文本和ExceptionType:例外名称(例如System.ArgumentExceptionSystem.Data.SqlClient.SqlException)。