我有很多个WCF服务方法,我想实现异常处理。我的服务将被.NET和非.NET客户端使用。故障契约是否是实现异常处理的唯一方法?如果是这样,我如何避免在我的服务中实现所有方法。我如何在一个地方实现异常处理以处理服务中所有方法的异常。请提供一些代码以便于理解。
以下是我的示例代码:
我的故障契约
以下是我的示例代码:
我的故障契约
[DataContract()]
public class FleetCustomException
{
[DataMember()]
public string Title;
[DataMember()]
public string ExceptionMessage;
[DataMember()]
public string InnerException;
[DataMember()]
public string StackTrace;
}
我的服务合同
[ServiceContract]
public interface IAddress
{
[OperationContract]
[FaultContract(typeof(FleetCustomException))]
bool SaveAddress(string address1, string address2, string address3, string city, string province, string postalCode,string country,bool isDeleted, int createdBy, DateTime createdDate, int lastModifiedBy, DateTime lastModifiedDate);
[OperationContract]
[FaultContract(typeof(FleetCustomException))]
bool DeleteAddress(Int64 addressID, int lastModifiedBy);
[OperationContract]
[FaultContract(typeof(FleetCustomException))]
List<Address> GetAllAddresses();
}
服务
public class SettingsService : IAddress
{
#region IAddress Members
public bool SaveAddress(string address1, string address2, string address3, string city, string province,string postalCode,string country, bool isDeleted,int createdBy, DateTime createdDate, int lastModifiedBy, DateTime lastModifiedDate)
{
try
{
Address address = new Address(0, address1, address2, address3, city, province, postalCode, country, isDeleted,createdBy, createdDate, lastModifiedBy, lastModifiedDate);
return address.Insert();
}
catch (FaultException ex)
{
FleetCustomException ex = new FleetCustomException();
ex.Title = "Error Funtion:SaveAddress()";
ex.ExceptionMessage = "Error occur while doing save address function.";
ex.InnerException = "Inner exception message from serice";
ex.StackTrace = "Stack Trace message from service.";
throw new FaultException(ex,"Reason: Testing the Fault contract") ;
}
}
public bool DeleteAddress(Int64 addressID, int lastModifiedBy)
{
Address address = new Address(addressID, lastModifiedBy);
return address.Delete();
}
public List<Address> GetAllAddresses()
{
Address address = new Address();
return address.GetAllAddresses();
}
#endregion
服务层中的配置包括在 <serviceDebug>
中设置 includeExceptionDetailInFaults="true"。
<serviceDebug includeExceptionDetailInFaults="true"/>
消费方法
try
{
MySettingsService.SettingsService proxy = new MySettingsService.SettingsService();
proxy .SaveAddress(Address1TextBox.Text, Address2TextBox.Text, "", "", "", "641025", "", false, 1, DateTime.Now, 0, DateTime.Now);
}
catch (FaultException<MyCalculatorService.CustomException> ex)
{
//Process the Exception
}
我需要在所有的服务方法中实现这个功能,但是我的方法有100多个,有没有一种快速且有效的方法来实现它?