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
/// <summary> /// Error message entity class (for FaultContract)/// </summary> [DataContract] public class FaultMessage { /// <summary> /// error message /// </summary> [DataMember] public string Message { get; set; } /// <summary> /// Error code /// </summary> [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>
/// <summary> /// Hello class/// </summary> public class Hello : IHello { /// <summary> /// Throw a FaultException<T> exception /// </summary> public void HelloFaultExceptionGeneric() { throw new FaultException<FaultMessage>(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 (<> 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.