In WCF, error handling is implemented primarily through the use of
FaultException<T> and service behaviors like IErrorHandler. This helps return
typed, user-friendly errors to clients instead of raw exceptions.
1. Using FaultException<T> for Typed Faults
Define a Fault Contract
[DataContract]
public class MyCustomFault
{
[DataMember]
public string ErrorMessage { get; set; }
[DataMember]
public string Details { get; set; }
}
public class MyService : IMyService
{
public string GetData(int id)
{
if (id < 0)
{
var fault = new MyCustomFault
{
ErrorMessage = "Invalid ID.",
Details = "ID must be non-negative."
};
throw new FaultException<MyCustomFault>(fault, "Input validation failed.");
}
return $"Data for ID: {id}";
}
}
2. Catching Faults on the Client Side
try
{
var result = client.GetData(-1);
}
catch (FaultException<MyCustomFault> ex)
{
Console.WriteLine("Service error: " + ex.Detail.ErrorMessage);
}
3. Unhandled Exceptions — Use IErrorHandler
For unhandled server exceptions, implement IErrorHandler to catch and convert them into fault messages:
public class GlobalErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
// Logging logic here
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
var customFault = new MyCustomFault
{
ErrorMessage = "Server Error",
Details = error.Message
};
var faultException = new FaultException<MyCustomFault>(customFault);
MessageFault msgFault = faultException.CreateMessageFault();
fault = Message.CreateMessage(version, msgFault, faultException.Action);
}
}
Hook into WCF via Behavior
public class ErrorBehavior : IServiceBehavior
{
public void ApplyDispatchBehavior(ServiceDescription desc, ServiceHostBase host)
{
foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
{
dispatcher.ErrorHandlers.Add(new GlobalErrorHandler());
}
}
// Other required interface methods (empty)
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In WCF, error handling is implemented primarily through the use of
FaultException<T>and service behaviors likeIErrorHandler. This helps return typed, user-friendly errors to clients instead of raw exceptions.1. Using
FaultException<T>for Typed FaultsDefine a Fault Contract
Use
[FaultContract]on OperationsThrow
FaultException<T>from Service2. Catching Faults on the Client Side
3. Unhandled Exceptions — Use
IErrorHandlerFor unhandled server exceptions, implement
IErrorHandlerto catch and convert them into fault messages:Hook into WCF via Behavior
And add it to your host:
Summary
FaultException<T>[FaultContract]IErrorHandlerFaultException(generic)