Yes it is possible! I am trying to describe it in VB.NET (I mainly use C #, but I hope I will not make syntax errors). 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 # looks like
[WebMethod]
[ScriptMethod (UseHttpGet=true)]
public string GetData(int age)
{
if (age <= 0)
throw new ArgumentException("The parameter age must be positive.");
}
In the case of a negative input value, an exception raises ArgumentException(everything I explain remains unchanged for another exception, such as SqlException).
You now have JavaScript code that you use jQuery.ajaxto call the service. You can then deploy the code to support exception handling as follows:
$.ajax({
type: "GET",
url: "MyWebService.asmx/GetData",
data: {age: -5},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, xhr) {
},
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;
alert(text);
} else {
alert("error");
}
}
});
In case of an exception, we receive information about the error in the JSON format. We deserialize it for an object that has properties Message, ExceptionTypeand StackTracethen display an error message, for example, the following
Message: The parameter age must be positive.
Exception: System.ArgumentException
, , StackTrace. Message: ExceptionType: (, System.ArgumentException System.Data.SqlClient.SqlException).