WCF-Global Exception Handling using IErrorHandler

Global Exception Handling – IServiceBehavior and IErrorHandler
To demonstrate this we need to create an ErrorHandler class by implementing the IErrorHandler and also a ServiceBehaviorAttribute class by impementing a IServiceBehavior. IServiceBehavior allows you to implement a service behaviour attribute which takes a custom error handler parameter which implements IErrorHandler

The IErrorHandler type exposes two methods. HandleError and ProvideFault.

  • Use the HandleError method to implement error-related behaviors such as error logging, system notifications, shutting down the application, and so on, and return a value that specifies whether the exception has been handled appropriate.
  • ProvideFault enables the creation of a custom FaultException<TDetail> that is returned to to the client from an exception in the course of a service method.

The IServiceBehavior type exposes three methods. AddBindingParameters, ApplyDispatchBehavior and Validate. For this article we are much interested only in ApplyDispatchBehavior method.

  • Here AddBindingParameters provides the ability to pass custom data to binding elements to support the contract implementation.
  • ApplyDispatchBehavior provides the ability to change run-time property values or insert custom extension objects such as error handlers, message or parameter interceptors, security extensions, and other custom extension objects.
  • Use the Validate method to confirm whether the current service can execute properly according to your scenario.

How it works

Whenever an unhandled exception occurs in a service decorated with the service behaviour attribute, two methods on the global error handler are called automatically: ProvideFault which allows you to construct a FaultException (rather than let ServiceModel do it), and HandleError which is intended for logging. The ProvideFault method is called first on the worker thread that is invoking the service call and HandlerError is called asynchronously on a separate thread, so lengthy logging operations don’t block the service request thread from sending a FaultException back to the client immediately.

WCF Global Exception Handling

Read more from CodeProject.com

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s