SoFunction
Updated on 2025-03-08

Exception handling of WCF

introduce

WCF (Windows Communication Foundation) - Exception handling: general Exception handling, FaultException and FaultException<T> throw and handle exceptions using IErrorHandler.

The third exception is introduced below: throwing and handling of FaultException<T>

1. Strongly type a SOP error class, and use [DataContract] to pass it

/// &lt;summary&gt;
/// Error message entity class (for FaultContract)/// &lt;/summary&gt;
[DataContract]
public class FaultMessage
{
    /// &lt;summary&gt;
    /// error message    /// &lt;/summary&gt;
    [DataMember]
    public string Message { get; set; }

    /// &lt;summary&gt;
    /// Error code    /// &lt;/summary&gt;
    [DataMember]
    public int ErrorCode { get; set; }
}

2. Use the [FaultContract] error agreement to specify the error type in the operation agreement

[ServiceContract]
public interface IHello
{
    [OperationContract]
    [FaultContract(typeof(FaultMessage))]
    void HelloFaultExceptionGeneric();
}

3. In the implementation code, define a method that can throw an exception of FaultException<FaultMessage>

/// &lt;summary&gt;
/// Hello class/// &lt;/summary&gt;
public class Hello : IHello
{
    /// &lt;summary&gt;
    /// Throw a FaultException<T> exception    /// &lt;/summary&gt;
    public void HelloFaultExceptionGeneric()
    {
        throw new FaultException&lt;FaultMessage&gt;(new FaultMessage { Message = "Throw FaultException<T>Exception", ErrorCode = -1 }, "For testing FaultException<T>");
    }
}

4. In the client, the exception of FaultException<FaultMessage> can be caught. FaultMessage is accessed with the Detail property.

protected void btnHelloFaultExceptionGeneric_Click(object sender, EventArgs e)
{
     proxy = new ();
    try
    {
        ();
    }
    catch (&lt;&gt; ex)
    {
         = ("Error code:{0};error message:{1};Cause of error:{2}",
            (),
            ,
            ());
    }
    finally
    {
        ();
    }
}

This is all about this article about WCF exception handling. I hope it will be helpful to everyone's learning and I hope everyone will support me more.