views:

191

answers:

1

Im calling a WCF service from jquery ajax. Sometimes the service throw some custom errors and when it does I need to get the message of that error. In the error function of my ajax call I have the following code:

            error: function(data) {
              alert("responseText: " + data.responseText);
            }

And the responseText when the error is thrown looks something like:

responseText: {"ExceptionDetail":{"HelpLink":null,"InnerException":null,"Message":"Denied",......}}

I want to get the "Message" from "ExceptionDetail" but I'm not sure how to do it.

My WCF service looks like this, to test it I just throw an error:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public string myFunction(string id)
{
    throw new Exception("Denied");
}

How can I get the Message of the error?

+1  A: 

By default, WCF will not return any exception details - that is a wanted feature, by design, in order not to divulge too much information back to a possible attacker.

If you want to enable detailed exception messages, you can do this by enabling a behavior on the server side:

 <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="debugBehavior">
          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <services>
        <service name="YourService"
                 behaviorConfiguration="debugBehavior">
             .....
        </service>
    </services>

But even now - you need to be aware that WCF should be interoperable, thus a client might not be running on .NET --> therefore you cannot just simply throw back an exception - that's a .NET specific construct.

Your best option is to catch all exceptions on the server (using e.g. the IErrorHandler interface), and turning those into SOAP faults - the interoperable equivalent of a .NET exception. If you know that the other end is a .NET client at all times, you can easily convert a .NET exception into a FaultException<T> where T is your .NET exception.

When you do this, you can catch an exception on the client by trapping the FaultException<T>, and its .Detail property should contain the normal .NET exception as you know it (and that contains a .Message property with the exception message).

marc_s
Thanks really much!
Martin