现在我将所有WCF服务调用包装在以下try / catch块中,我想知道是否有办法在一个地方设置它并将其应用于所有服务调用。
try
{
Product test = client.GetProductById(1);
}
catch (TimeoutException ex)
{
WPFMessageBox.Show("The service operation timed out." + ex.Message);
}
catch (FaultException<CustomFault> ex)
{
WPFMessageBox.Show("CustomFault:" + ex.ToString());
}
catch (FaultException ex)
{
WPFMessageBox.Show("Unknown Fault:" + ex.ToString());
}
catch (CommunicationException ex)
{
WPFMessageBox.Show("There was a communication problem" + ex.Message +
ex.StackTrace);
}
答案 0 :(得分:4)
您可以编写一个包装器方法来获取代码来执行委托传递的服务调用:
public T ServiceCallWrapper<T>(Func<T> serviceCallDelegate)
{
try
{
return serviceCallDelegate();
}
catch (TimeoutException ex)
{
WPFMessageBox.Show("The service operation timed out." + ex.Message);
}
catch (FaultException<CustomFault> ex)
{
WPFMessageBox.Show("CustomFault:" + ex.ToString());
}
catch (FaultException ex)
{
WPFMessageBox.Show("Unknown Fault:" + ex.ToString());
}
catch (CommunicationException ex)
{
WPFMessageBox.Show("There was a communication problem" + ex.Message +
ex.StackTrace);
}
}
然后你可以用这样的匿名方法调用包装器:
Product test = ServiceCallWrapper<Product>(() => client.GetProductById(1));
答案 1 :(得分:1)
你可以通过AoP和IoC来做到这一点。
有一个代码示例。