【发布时间】:2012-01-03 16:24:08
【问题描述】:
我有 N 个 WCF 服务方法。我想实现异常处理。我的服务将被 .net 和非 .net 客户端使用。故障契约是实现异常处理的唯一方法吗?如果这意味着我如何避免实现我的服务中的所有方法。我如何在一个地方实现异常处理来处理我的服务中所有方法的异常。请提供一些代码集以轻松稳定。
这是我的示例代码。
MyFaultContract
[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
}
Service 层中的配置 includeExceptionDetailInFaults="true" in <serviceDebug>
<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 种方法有什么方法可以快速有效地实现它
【问题讨论】:
-
你想完成什么?根本不处理异常有什么问题?
-
嗨,约翰,如果我只处理异常。不在 .net 框架中的其他程序将无法理解该异常。这样 WCF 故障合同将发送基于 XML 肥皂的异常。
-
还是会出现 SOAP 故障,只是没有详细说明。
标签: wcf