Handle WCF Fault in Silverlight

Run into this thread on stackoverflow about handling fault in asynchronous call.

  • In normal .NET code, the generated proxy class handles the exception properly by putting the exception in the Error property instead of throwing it.
  • In Silverlight, the generated proxy class sets the Error property, but does not handle the exception completely. The exception is picked up by the debugger, which pops up the exception box with the message “ProtocolException was unhandled by user code”. Despite this message, the exception does not seem to actually make it to the Application_UnhandledException function.

In my opinion, Silverlight is running within browser, in theory, it should rely on browser to handle all the exceptions, similar to javascript and flash. Asynchronous call makes this fault handling more complex, putting regular try catch block on the primary call doesn’t work,  Microsoft doesn’t add try catch block in OnComplete method in generated proxy.cs either.

Instead customize proxy generation wizard, we use a pipeline pattern to introduce a extra layer between silver light and wcf proxy.

This pipe line (wrapper) class is replacing the original WCF proxy inject into SL view model, in it’s ctor the new complete event handler will be appended after the one with the same name in proxy.

General Exception handling is happening in CheckError() method.

Here are some example code:

        public MySilverLightViewModel(IMySilverLightDataService dataService)
            // Hookup DataAccess Completed Events
            _dataService = dataService;

            _dataService.DataServiceCallCompleted += (s, e) =>
                    IsBusy = false; // used by UI control to display the spinner

                    if (e.Error.GetType() == typeof (FaultException<TooManyRecordsFault>)) // deal with FaultContract defined in OperationContract
                        DialogueService.ShowAlert(e.Error.Message);  // Our own message box service

                    if (_dataService.ErrorCheck(e)) return;  // general unhandled exception happend in ErrorCheck, stop call if occurs.

                    // processing data ...

Maybe we will re-visit this after we got chance to look into RIA service.


Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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


Connecting to %s