Monday, February 21, 2011

Programmatic configuration of Exception-sending in WCF

I would like my Silverlight client to be able to display exceptions that have happened at the server during a WCF call.

Given my current code to create a WCF Channel (on the client):

// create the binding elements
BinaryMessageEncodingBindingElement binaryMessageEncoding = new BinaryMessageEncodingBindingElement();
HttpTransportBindingElement httpTransport = new HttpTransportBindingElement() { MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue };

// add the binding elements into a Custom Binding
CustomBinding customBinding = new CustomBinding(binaryMessageEncoding, httpTransport);

// create the Endpoint URL 
EndpointAddress endpointAddress = new EndpointAddress(serviceUrl);

      // create an interface for the WCF service
ChannelFactory<TWcfApiEndPoint> channelFactory=new ChannelFactory<TWcfApiEndPoint>(customBinding, endpointAddress);
channelFactory.Faulted += new EventHandler(channelFactory_Faulted);   
TWcfApiEndPoint client = channelFactory.CreateChannel();

return client;

When an exception occurs, I just get a "NotFound" exception, which is obviously of no use. How can I get the exception information?

I use this code to use the client object returned above:

try
{
// customFieldsBroker is the client returned above
        customFieldsBroker.BeginCreateCustomField(DataTypeID, newCustomField, (result) =>
        {
         var response = ((ICustomFieldsBroker)result.AsyncState).EndCreateCustomField(result);

    }, customFieldsBroker);
}
catch (Exception ex)
{
    // would like to handle exception here
}

Wrapping the Begin/End calls in a try { } catch { } block doesn't seem to even jump into the catch { } block.

If it matters, I'm using Silverlight 3 at the client.

From stackoverflow
  • Due to security limitations in the browser sandbox, silverlight can't see the body of server errors (status code 500). To get this working you need to make a change to the server side, to change the way it returns faults to the browser. There's an MSDN article that describes it in detail.

    Program.X : Thanks very much for your help. This has solved it. Although, I'm concerned about the web.config setting requirement: I seem to have have the complete Version= there, which I would like to avoid, as it is dynamically updated. Is there a way I can ignore this version number?
    alexdej : I _think_ it will still bind the type without the full name. What happens if you take out the Version?
  • You need to do two things:

    • declare the Fault exception as part of the contract
    • throw the exception as a fault exception

      [OperationContract]

      [FaultContract(typeof(ArithmeticFault))]

      public int Calculate(Operation op, int a, int b)

      { // ... }

      throw new FaultException();

0 comments:

Post a Comment