Get xhr object in vb.net while ajax calling fails

筅森魡賤 提交于 2019-12-06 16:25:31

Yes it is possible! I try to describe it in VB.NET (mostly I use C#, but I hope I'll not made syntax errors). Let us we have a Web service

<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

The same code in C# look like

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

In case of negative Age input the exception ArgumentException will be thrown (all what I explain stay the same for another exception like SqlException).

Now you have a JavaScript code which use jQuery.ajax to call the service. Then you can expand the code to support the exception handling in the following way:

$.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");
        }
    }
});

In case of exception be thrown, we receive information about error in JSON format. We deserialize it to the object having Message, ExceptionType and StackTrace property and then display error message like following

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

In a real application you will probably never displayed the value of the StackTrace property. The most important information are in the Message: the text of exception and in ExceptionType: the name of exception (like System.ArgumentException or System.Data.SqlClient.SqlException).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!