在服務端定義異常:
using System;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
namespace FaultExceptions
{
[ServiceContract ()]
public interface IFaultExceptionService
{
[OperationContract ]
[FaultContract (typeof (InvalidOperationException ))]
void ThrowSimpleFault();
[OperationContract ]
[FaultContract (typeof (InvalidOperationException ))]
void ThrowMessageFault();
[OperationContract ()]
[FaultContract (typeof (InvalidOperationException ))]
void ThrowFaultException();
}
public class FaultExceptionService : IFaultExceptionService
{
#region IService Members
public void ThrowSimpleFault()
{
throw new FaultException ("An invalid operation has occurred." );
}
public void ThrowMessageFault()
{
InvalidOperationException error = new InvalidOperationException ("An invalid operation has occurred." );
MessageFault mfault = MessageFault .CreateFault(new FaultCode ("Server" , new FaultCode (String .Format("Server.{0}" , error.GetType().Name))), new FaultReason (error.Message), error);
FaultException fe = FaultException .CreateFault(mfault, typeof (InvalidOperationException ));
throw fe;
}
public void ThrowFaultException()
{
FaultException <InvalidOperationException > fe = new FaultException <InvalidOperationException >(new InvalidOperationException ("An invalid operation has occured." ), "Invalid operation." , new FaultCode ("Server" , new FaultCode (String .Format("Server.{0}" , typeof (NotImplementedException )))));
throw fe;
}
#endregion
}
}
客戶端接收異常:
localhost.FaultExceptionServiceClient proxy = new Client.localhost.FaultExceptionServiceClient ();
try
{
Console .ForegroundColor = ConsoleColor .Yellow;
Console .WriteLine("Calling proxy.ThrowSimpleFault()" );
Console .WriteLine("" );
Console .ResetColor();
proxy.ThrowSimpleFault();
}
catch (FaultException fe)
{
Console .WriteLine(fe.GetType().ToString());
Console .WriteLine("ERROR: {0}" , fe.Message);
}
catch (Exception ex)
{
Console .WriteLine(ex.GetType().ToString());
Console .WriteLine("ERROR: {0}" , ex.Message);
}