是的,这是可能的!我尝试用 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 格式的错误信息。我们将其反序列化为具有Message、ExceptionType 和StackTrace 属性的对象,然后显示如下错误消息
Message: The parameter age must be positive.
Exception: System.ArgumentException
在实际应用程序中,您可能永远不会显示StackTrace 属性的值。最重要的信息在Message:异常文本和ExceptionType:异常名称中(如System.ArgumentException 或System.Data.SqlClient.SqlException)。