【问题标题】:Get xhr object in vb.net while ajax calling failsajax调用失败时在vb.net中获取xhr对象
【发布时间】:2011-04-07 19:13:06
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    是的,这是可能的!我尝试用 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)。

    【讨论】:

    • 不走运。更改 URL 并没有更改错误,并且使用您的错误代码,我只会收到一条显示“错误”的警报。不过谢谢!
    • @Oren 答:我的答案中的代码已简化,仅显示有关 Web 服务引发异常情况的错误详细信息。您在stackoverflow.com/questions/3650561/… 中描述的错误具有完全不同的性质。你有 textStatus=**parseerror**。所以你应该首先显示xhr.responseTextalert(xhr.responseText);
    猜你喜欢
    • 2022-11-30
    • 2017-03-09
    • 2020-01-31
    • 1970-01-01
    • 2011-07-15
    • 2014-04-08
    • 2019-01-25
    • 2022-01-07
    • 2012-06-17
    相关资源
    最近更新 更多