0

I searched a lot in the internet but could not be able to find any solution for my problem.

Problem

I have created two applications. One is WCF service application and another one is the main application that consumes WCF service operations through jQuery Ajax. Everything is working fine. Finally, I want to complete the task by adding code for error handling in WCF service. Now, I added "Fault Contract" in WCF service but cannot be able to understand how to pass the error from service to jQuery ajax directly. Right now, the custom error message is not being passed and the general service error message "Bad Request" is being passed.

WCF Service Code

[ServiceContract]
public interface IAdmin_UserDet
{
    [OperationContract]
    [FaultContract(typeof(ErrorHandler))]
    string getData();
}

[DataContract]
public class ErrorHandler
{
    [DataMember]
    public string message { get; set; }
    [DataMember]
    public string methodName { get; set; }
    [DataMember]
    public int lineNumber { get; set; }
    [DataMember]
    public string errorDateTime { get; set; }
}

[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class Admin_UserDet : IAdmin_UserDet
{
    [WebInvoke(Method = "GET", UriTemplate = "returnData", ResponseFormat = WebMessageFormat.Json)]
    public string getData()
    {
        try
        {
            int num1 = 2;
            int num2 = 0;

            int res = num1/num2;
            return res.ToString();
        }
        //catch(FaultException<ErrorHandler> objErr)
        catch(Exception ex)
        {
          ErrorHandler objErr = new ErrorHandler();
          objErr.message = "division by zero";
          objErr.methodName = "getData";
          //return objErr.Detail.message + " | " + objErr.Detail.methodName;
          throw new FaultException<ErrorHandler>(objErr);
        }
    }
}

jQuery Ajax Code (through which I am calling the service)

var wcfUrl = "http://localhost/VMService/Admin_UserDet.svc/";

 $('button[id=btnTest]').click(function () {
   $.ajax({
        type: "GET",
        url: wcfUrl + "returnData",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (response) {
                     alert("no error");
                     console.log(response);
        },
        error: function (e) {
                     console.log(JSON.parse(e.responseText));
        }
    });
});

Error Message which I am getting after running the application

GET http://localhost/VMService/Admin_UserDet.svc/returnData 400 (Bad Request)

But, I want the error message as "division by zero | getData", which has been set in getData Method.

Please guide me the exact way / any link from where I might get an idea about how to handle WCF errors from jquery ajax.

Thank you.

Agnib
  • 79
  • 1
  • 3
  • 11
  • You use FaultException in a .Net client, for your ajax client, throw a simple exception – Ricardo Pontual Oct 07 '15 at 12:15
  • Ok. You mean to say that I will use FaultException if I am consuming the service in .NET client (creating proxy class's object). For this case, as I am consuming through jquery ajax, so I do not need to use "FaultException", simple exception will work for me. Am I right? – Agnib Oct 07 '15 at 12:18
  • Yes it's right. There are some other ways, for example implement IErrorHandler, or if you're using json/rest methods, you can return the error in response object. – Ricardo Pontual Oct 07 '15 at 14:19
  • Actually, I am using json methods. I just put a simple text message in catch section and it is returning to my jquery ajax method. That's fine. But, I noticed that its coming in jquery ajax's success function and not error function. Technically, it should come inside error function isn't it? Because, in the service, its coming inside catch(), so it means that exception has occurred and then it should come inside jquery ajax error() instead of success(). I can be able to handle if it come inside success(), that's not a problem. But, I would like to understand the flow how its actually working. – Agnib Oct 08 '15 at 05:51
  • Implement IErrorHandler which will return proper json error for jQuery and inject it via behavior. See the link below in my answer. – Mimas Oct 08 '15 at 08:38
  • @Mimas - I saw it but I did not understand how to implement it. – Agnib Oct 08 '15 at 10:05
  • @RicardoPontual - I faced another problem. My function is returning a specific class type object. So, in catch(), I cannot be able to return any formatted string as the return type is getting mismatched. – Agnib Oct 08 '15 at 10:07
  • Well, I think that IErrorHandler is the perfect solution. I will go through the link one more time @Mimas. If I face any issues then please do help me Ricardo and Mimas. Anyways, thanks a lot to both of you. – Agnib Oct 08 '15 at 10:26
  • Does your service receive other calls which need to return a soap response? I'm asking because if the client for this service is just this javascript code, you could simply implement a web api method, it's easy and you can return an object with success response or error to your client. See this example: http://stackoverflow.com/questions/28298276/returning-an-error-message-to-an-end-user-upon-exception-in-webapi-methods – Ricardo Pontual Oct 08 '15 at 11:09
  • Well, I can understand that web api would be good enough. But, there are lots of operation contracts being written in the service and none of them has the error handling code. Now, I have been assigned task to handle errors in all the existing operations. – Agnib Oct 09 '15 at 05:53

1 Answers1

0

I believe this was answered here, regardless this is not marked as an answer. I personally used same approach, worked perfectly for me.

Community
  • 1
  • 1
Mimas
  • 525
  • 3
  • 7