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