How to take care of unhandled exceptions in WCF Services
- November 22nd, 2009
- Posted in Tech Recipes . WCF
- By Germán Medina
- Write comment
When developing web services using WCF it’s considered a good practice to take care of unhandled exceptions. In this post I’ll explain an easy way to log your WCF unhandled errors and create a custom message.
First you will need to create a class that inherits from Attribute and implements IServiceBehavior and IErrorHandler interfaces. Inheritance from Attribute will allow us to use our new class as metadata for our service. IServiceBehavior interface makes our new class a custom extension for a service and IErrorHandler will give us control over service faults. As you can think we will be creating a new service behavior that handles errors and will be assigned to our service as a metadata attribute. This is the code for our custom error handler:
public class ErrorHandlerAttribute : Attribute, IServiceBehavior, IErrorHandler
{
public bool HandleError(Exception e)
{
EventLog log = new EventLog();
log.Source = "Your Application Name";
log.WriteEntry(e.Message + "\n" + e.StackTrace, EventLogEntryType.Error);
return true;
}
public void ProvideFault(Exception error,
MessageVersion ver,
ref System.ServiceModel.Channels.Message msg)
{
FaultException fe = new FaultException("Your Custom Error");
MessageFault fault = fe.CreateMessageFault();
msg = System.ServiceModel.Channels.Message.CreateMessage(ver, fault, null);
}
public void AddBindingParameters(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
{
}
public void Validate(ServiceDescription serviceDescription,
ServiceHostBase serviceHostBase)
{
}
}
The AddBindingParameters, ApplyDispatchBehavior and Validate methods will need no implementation. We just need to take care of HandleError method for logging and ProvideFault method to create our custom error message.
After that all you need to do is annotate your service class with the error handler:
[ErrorHandler]
public class Service : IService
{
}
No comments yet.