When we work with jQuery Ajax call to WCF, it may possible that WCF service will thow an exception. And we need to catch that exception in jquery ajax error routine. In order to show or get exception thrown by service we need to configure includeExceptionDetailInFaults="True" for in behavior like:
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
Now when jquery ajax call revices error then exception comes in resposeText as Message.But we need extract Message from responseText as responseText comes as cominations of error details. This can be done using jQuery.parseJSON like:
.error(function (response, q, t) {
var r = jQuery.parseJSON(response.responseText);
});
Now to get Message part we can use r.Message. This will give you the message that is sent by exception in wcf service.
.error(function (response, q, t) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
});
Code for jQuery ajax handle exception thrown by wcf
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<title>Jquery ajax json call to wcf service</title>
<script type="text/javascript">
$(document).ready(function () {
$("#btnClick").click(function () {
var dto = { message: $("#messageinput").val() };
$.ajax({
type: 'GET',
url: '<%= ResolveUrl("~/Service1.svc/get-json/GetMessage") %>',
data: dto,
contentType: "application/json; charset=utf-8"
})
.success(function (response) {
alert(response.d);
})
.error(function (response, q, t) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
alert("ERROR" + response.d);
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="messageinput" />
<asp:Button ID="btnClick" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
Note: To test example of catch exception in jquery ajax thrown by wcf service, just throw an application exception or Exception with some message like:
[WebGet()]
[OperationContract]
public string GetMessage(string message)
{
//return "WCF" + message;
throw new ApplicationException("This is exception");
}