ajax vb2005,web services - Get xhr object in vb.net while ajax calling fails - Stack Overflow

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

_

_

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值