【发布时间】:2014-02-23 22:47:39
【问题描述】:
我在各种项目中多次遇到这个问题,我想知道是否有比我通常最终使用的解决方案更好的解决方案。
假设我们有一系列需要执行的方法,并且我们想知道其中一个方法是否出现问题并优雅地中断(可能撤消任何以前的更改......),我通常会这样做以下(伪 C#,因为这是我最熟悉的):
private bool SomeMethod()
{
bool success = true;
string errorMessage = null;
success = TestPartA(ref errorMessage);
if (success)
{
success = TestPartB(ref errorMessage);
}
if (success)
{
success = TestPartC(ref errorMessage);
}
if (success)
{
success = TestPartD(ref errorMessage);
}
//... some further tests: display the error message somehow, then:
return success;
}
private bool TestPartA(ref string errorMessage)
{
// Do some testing...
if (somethingBadHappens)
{
errorMessage = "The error that happens";
return false;
}
return true;
}
我只是想知道(这是我的问题)是否有更好的方法来应对这种事情。我似乎最终写了很多 if 声明,因为它看起来应该更流畅。
有人建议我对一组委托函数进行循环,但我担心这会过度设计解决方案,除非有一种干净的方法来做到这一点。
【问题讨论】:
-
如果这些确实是错误,那么您可能应该抛出异常。
标签: c# asp.net design-patterns error-handling custom-error-handling