Silverlight and WCF exception handling

A colleage asked me why he got “not found” expections in his Silverlight client whenever an exception was returned from my WCF service. My answer was this is a Silverlight problem and needs to be resolved by you. But I offered him to snif the messages with fiddler.
The exception was serialized and send to the silverlight client. There seemed to be nothing wrong with the WCF. But why the “not found” exception in stead of the actual exception?
After reading this post by John Papa: I noticed the HTTP error stacktrace in the Silverlight client. Seems that the async pattern Silverlight uses can’t handle HTTP500+ statuscodes. The offered solution uses a endpointbehavior that resets the statuscode to HTTP200 whenever a fault is returned.

// This is only part of the actual code
public class SilverlightFaultBehavior : BehaviorExtensionElement, IEndpointBehavior
        public class SilverlightFaultMessageInspector : IDispatchMessageInspector
            public void BeforeSendReply(ref Message reply, object correlationState)
                if (reply.IsFault)
                    HttpResponseMessageProperty property = new HttpResponseMessageProperty();
                    // Here the response code is changed to 200.
                    property.StatusCode = System.Net.HttpStatusCode.OK;
                    reply.Properties[HttpResponseMessageProperty.Name] = property;

We decided to create a datacontract that returns aditional exception information and added a try-catch to the toplevel implementation of the WCF service. Whenever an exception is thrown in the service a default of the datacontract is created in the catch block and exception information is added for debugging. Now we don’t need special behaviors for Silverlight.

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.