许多方法的捕获代码相同

Hen*_*hiu 2 .net c#

我有几个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
   }
}
Run Code Online (Sandbox Code Playgroud)

Ily*_*nov 9

这个功能解决方案怎么样?注意我不会吞下异常并使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果需要返回某个值,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;
    }
}
Run Code Online (Sandbox Code Playgroud)