【问题标题】:Is there a way to handle WCF server faults in one spot on the client?有没有办法在客户端的一个位置处理 WCF 服务器故障?
【发布时间】:2011-05-28 11:31:28
【问题描述】:

现在我将所有 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);
}

【问题讨论】:

    标签: wpf wcf exception-handling


    【解决方案1】:

    您可以编写一个包装器方法来获取执行委托传入的服务调用的代码:

    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));
    

    【讨论】:

    • 谢谢,很简单。
    • Jan,这个包装器如何查找接受一个或多个参数但不返回值的方法? (例如是无效的。)(例如:内部静态无效 LockoutUser(字符串用户 ID,int timeInSeconds))
    • @FarrEver,在ServiceCallWrapper方法中用Action交换Funcpublic void ServiceCallWrapper(Action serviceCallDelegate)
    【解决方案2】:

    您可以通过 AoP 和 IoC 做到这一点。

    我在这里写了如何: http://pablocastilla.wordpress.com/2010/11/09/aop-and-ioc-in-wcf-4-0-with-enterprise-library-5-and-appfabric-part-1/

    有一个代码示例。

    【讨论】:

    • 我不确定我是否理解如何在客户端捕获服务器故障。你能解释一下吗?
    • 您会将它们视为 AoP 样式。通过企业库配置,您可以配置客户端以便以不同方式处理异常。
    • 谢谢,我想改天再调查一下,但现在我没有时间,所以接受了 Jan 的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多