---
title: "How do you implement error handling in WCF (e.g., using FaultException)?"  
description: "How do you implement error handling in WCF (e.g., using FaultException)?"  
author: "ICSM Computer"  
published: 2025-05-28  
updated: 2025-05-28  
canonical: https://www.mindstick.com/interview/34177/how-do-you-implement-error-handling-in-wcf-e-g-using-faultexception  
category: "c#"  
tags: ["c#", "wcf"]  
reading_time: 4 minutes  

---

# How do you implement error handling in WCF (e.g., using FaultException)?

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

```cs
[DataContract]
public class MyCustomFault
{
    [DataMember]
    public string ErrorMessage { get; set; }

    [DataMember]
    public string Details { get; set; }
}
```

### Use `[FaultContract]` on Operations

```cs
[ServiceContract]
public interface IMyService
{
    [OperationContract]
    [FaultContract(typeof(MyCustomFault))]
    string GetData(int id);
}
```

### Throw `FaultException<T>` from Service

```cs
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

```cs
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:

```cs
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

```cs
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)
}
```

And add it to your host:

```cs
serviceHost.Description.Behaviors.Add(new ErrorBehavior());
```

## Summary

| Technique | Purpose |
| --- | --- |
| `FaultException<T>` | Return typed, known faults |
| `[FaultContract]` | Declare fault types in WSDL |
| `IErrorHandler` | Catch and convert unhandled exceptions |
| `FaultException` (generic) | Send general error with message string |

## Answers

### Answer by ICSM Computer

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

```cs
[DataContract]
public class MyCustomFault
{
    [DataMember]
    public string ErrorMessage { get; set; }

    [DataMember]
    public string Details { get; set; }
}
```

### Use `[FaultContract]` on Operations

```cs
[ServiceContract]
public interface IMyService
{
    [OperationContract]
    [FaultContract(typeof(MyCustomFault))]
    string GetData(int id);
}
```

### Throw `FaultException<T>` from Service

```cs
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

```cs
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:

```cs
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

```cs
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)
}
```

And add it to your host:

```cs
serviceHost.Description.Behaviors.Add(new ErrorBehavior());
```

## Summary

| Technique | Purpose |
| --- | --- |
| `FaultException<T>` | Return typed, known faults |
| `[FaultContract]` | Declare fault types in WSDL |
| `IErrorHandler` | Catch and convert unhandled exceptions |
| `FaultException` (generic) | Send general error with message string |


---

Original Source: https://www.mindstick.com/interview/34177/how-do-you-implement-error-handling-in-wcf-e-g-using-faultexception

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
