2013-03-28 54 views
0

我有几个C#方法,我想包装在try-catch块中。每个函数都有相同的逻辑。有没有一种优雅的方式来添加一个装饰器到这些函数中的每一个,所以它们都被相同的try/catch块包装?我不想将try/catch块添加到所有这些函数中。许多方法的相同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 
    } 
} 
+0

你能证明你的代码...... –

+6

为什么不干脆的try/catch每发送异常普通的静态函数? –

+0

@JoelEtherton我该怎么去做这件事,你有没有例子? –

回答

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; 
    } 
} 
+0

谢谢!你的代码很有用!我遇到了一个问题,如果所有的函数(WrapFunctionCallWithReturn除外)都接受ref参数,它会导致错误:“不能在匿名方法内使用ref或out参数...”。我们通过暂时解决问题,然后在通话后重新分配;有没有办法使用这个解决方案与ref或out参数? – user3282085

+0

和异步?你喜欢: 'VAR的结果=等待WrapFunctionCallWithReturn(()=> DoSomething的(5));' 'VAR的结果= WrapFunctionCallWithReturn(()=>等待DoSomething的(5));' – fantastory

+0

我明白了: 'var result = await WrapFunctionCallWithReturn(()=> DoSomething(5));' 是必须的 - await必须在try catch里面 – fantastory

2

这是乔尔·埃瑟顿的评论转述作为一个答案。请注意,这不是最好的解决方案(请参阅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); 
    } 
} 
+2

真棒用户名! – joshgo

相关问题