许多方法的catch代码相同

本文关键字:代码 catch 方法 许多 | 更新日期: 2023-09-27 18:06:25

我有几个c#方法,我想在try-catch块中包装。每个函数都有相同的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
   }
}

许多方法的catch代码相同

有什么功能性的解决方案吗?注意,我没有吞下异常并使用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;
    }
}

这是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);
   }
}