如何将每个WCF调用封装在try-catch块中



我有一个网站,需要在那里对WCF服务进行异步调用。我想将每个调用封装在try-catch块中,这样我就可以处理TimeoutException和CommunicationException。

然而,我不想每次调用我的服务时都复制粘贴完全相同的try-catch块。有没有什么方法可以使用委托只写一次try-catch块?我还想捕获异常消息。

我想这样称呼它:

// This method returns void
TryCatchHelper(x => x.WCFMethod1(param1, param2));
// This method has a return value but no params
var returnValue = TryCatchHelper(x => x.WCFMethod2());

编辑:以下是我的代码现在的样子:

User GetUser(int Id)
{
    User returnUser = null;
    try
    {
        // Open WCF channel, etc.
        returnUser = myWCFClient.GetUser(Id);
    }
    catch (TimeoutException exception)
    {
        Log(exception.Message);
        // Abort WCF factory
    }
    catch (CommunicationException exception)
    {
        Log(exception.Message);
        // Abort WCF factory
    } 
    return returnUser;
}

我不想在我在存储库中设置的每一个方法中都使用相同的try-catch块。我试着做这样的事情,但它在参数上给了我一个错误。我知道我没有正确使用它们,但我需要一种方法来定义一个可以代替我想要进行的所有WCF方法调用的委托:

delegate object WCFAction(params object[] parameters);
object DoWCFAction(WCFAction action, params object[] parameters)
{
    object returnValue = null;
    try
    {
        // Open WCF channel, etc.
        returnValue = action(parameters);
    }
    catch (TimeoutException exception)
    {
        Log(exception.Message);
        // Abort WCF factory
    }
    catch (CommunicationException exception)
    {
        Log(exception.Message);
        // Abort WCF factory
    } 
    return returnValue;
}
void MainMethod()
{
    // Compiler error
    User user = DoWCFAction(GetUser, 1);
}

您可以设置这样的类。抱歉,这里有两个异常处理程序,而不是一个:

class Logger
{
    // handle wcf calls that return void
    static public void ExecWithLog(Action action)
    {
        try
        {
            action();
        }
        catch(Exception e)
        {
            Log(e);
            throw;
        }
    }
    // handle wcf calls that return a value
    static public T ExecWithLog<T>(Func<T> action)
    {
        T result = default(T);
        try
        {
            result = action();
        }
        catch (Exception e)
        {
            Log(e);
            throw;
        }
        return result;
    }
    static void Log(Exception e)
    {
        System.Diagnostics.Debug.WriteLine(e.ToString());
    }
}

然后,调用您的方法:

static void Main(string[] args)
{
    Logger.ExecWithLog(() => DoSomethingReturnVoid());
    Logger.ExecWithLog(() => DoSomethingReturnVoidParamInt(5));
    int a = Logger.ExecWithLog<int>(() => DoSomethingReturnInt());
    string b = Logger.ExecWithLog<string>(() => DoSomethingReturnStringParamInt(5));
}

使用WCF的正确方法是使用扩展。看看这些关于WCF扩展的文章:

  • https://msdn.microsoft.com/en-us/magazine/cc163302.aspx
  • http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/17/wcf-extensibility-ioperationinvoker.aspx

最新更新