许多方法的捕获代码相同

时间:2013-03-28 14:37:49

标签: c# .net

我想要在try-catch块中包装几个C#方法。每个函数对catch都有相同的逻辑。有没有一种优雅的方法来为这些函数添加一个装饰器,所以它们都用相同的try / catch块包装?我不想将try / catch块添加到所有这些函数中。

示例:

public void Function1(){
   try {
     do something
   }catch(Exception e) {
      //a BUNCH of logic that is the same for all functions
   }
}

public void Function2() {
   try {
     do something different
   }catch(Exception e) {
      //a BUNCH of logic that is the same for all functions
   }
}

2 个答案:

答案 0 :(得分:8)

对此有哪些功能性解决方案?注意我不会吞下异常并使用throw;语句,这将重新抛出异常,保持原始堆栈跟踪。不要默默地吞下异常 - 它被认为是一种非常糟糕的做法,然后调试代码变得非常可怕。

void Main()
{
    WrapFunctionCall( () => DoSomething(5));
    WrapFunctionCall( () => DoSomethingDifferent("tyto", 4));
}

public void DoSomething(int v){ /* logic */}

public void DoSomethingDifferent(string v, int val){ /* another logic */}

public void WrapFunctionCall(Action function) 
{
    try
    {
        function();
    }
    catch(Exception e)
    {
         //a BUNCH of logic that is the same for all functions
         throw;
    }
}

如果您需要返回某个值,WrapFunctionCall方法的签名将会更改

void Main()
{
    var result = WrapFunctionCallWithReturn( () => DoSomething(5));
    var differentResult = WrapFunctionCallWithReturn( () => DoSomethingDifferent("tyto", 4));
}

public int DoSomething(int v){ return 0; }

public string DoSomethingDifferent(string v, int val){ return "tyto"; }

public T WrapFunctionCallWithReturn<T>(Func<T> function) 
{
    try
    {
        return function();
    }
    catch(Exception e)
    {
        //a BUNCH of logic that is the same for all functions
        throw;
    }
}

答案 1 :(得分:2)

这是Joel Etherton的评论作为答案的解释。请注意,这不是最佳解决方案(请参阅Ilya Ivanov的答案以获得更好的解决方案) 但这很简单,如果我正确地阅读了你的问题,那正是你所要求的:

void errorHandling(Exception e)
{
  // Your BUNCH of logic
}

public void Function1(){
   try {
     do something
   }catch(Exception e) {
      errorHandling(e);
   }
}

public void Function2() {
   try {
     do something different
   }catch(Exception e) {
      errorHandling(e);
   }
}