Mic*_*ern 5 c# design-patterns try-catch
情况:
我的应用程序需要处理业务规则的第一步(初始的try-catch语句).如果进程在该步骤中调用辅助方法时发生某个错误,我需要切换到catch语句中的第二个进程.备份过程使用相同的帮助程序方法.如果在第二个进程中发生同样的错误,我需要停止整个进程并抛出异常.
执行:
我打算在第一个try-catch陈述的catch陈述中插入另一个try-catch陈述.
//run initial process
try
{
//initial information used in helper method
string s1 = "value 1";
//call helper method
HelperMethod(s1);
}
catch(Exception e1)
{
//backup information if first process generates an exception in the helper method
string s2 = "value 2";
//try catch statement for second process.
try
{
HelperMethod(s2);
}
catch(Exception e2)
{
throw e2;
}
}
Run Code Online (Sandbox Code Playgroud)
这个代码有异味吗?如果是的话,什么是更好的设计模式来避免这种情况?
编辑
我引起了一些混淆,并忽略了当第一个进程失败并切换到第二个进程时,它会向辅助方法发送不同的信息.我已更新方案以反映整个过程.
Hen*_*man 12
如果HelperMethod需要第二次尝试,那么这没有什么直接的错误,但是catch中的代码试图做得太多,它会破坏e2中的堆栈跟踪.
你只需要:
try
{
//call helper method
HelperMethod();
}
catch(Exception e1)
{
// maybe log e1, it is getting lost here
HelperMethod();
}
Run Code Online (Sandbox Code Playgroud)