[英]Design Pattern for Error Handling
我在各个项目中遇到过这个问题几次,我想知道是否有比我通常最终使用的解决方案更好的解决方案。
假设我们有一系列需要执行的方法,并且我们想知道其中一个方法中是否出现问题并优雅地突破(可能撤消任何先前的更改......),我通常会执行以下操作(伪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
语句似乎应该更流畅。
我被建议在一组委托函数上进行循环,但是我担心这会过度设计解决方案,除非有一个干净的方法来完成它。
我认为你应该使用例外。 请注意,通常只应在应用程序的“顶层”捕获异常。
private void TopLevelMethod()
{
try
{
SomeMethod();
}
catch (Exception ex)
{
// Log/report exception/display to user etc.
}
}
private void SomeMethod()
{
TestPartA();
TestPartB();
TestPartC();
TestPartD();
}
private void TestPartA()
{
// Do some testing...
try
{
if (somethingBadHappens)
{
throw new Exception("The error that happens");
}
}
catch (Exception)
{
// Cleanup here. If no cleanup is possible,
// do not catch the exception here, i.e.,
// try...catch would not be necessary in this method.
// Re-throw the original exception.
throw;
}
}
private void TestPartB()
{
// No need for try...catch because we can't do any cleanup for this method.
if (somethingBadHappens)
{
throw new Exception("The error that happens");
}
}
我在我的例子中使用了内置的System.Exception类; 您可以创建自己的派生异常类,也可以使用从System.Exception派生的内置类。
您也许可以尝试查看SOLID原则的“打开/关闭”部分。 在您的示例中,您可以创建一个ITestRule
接口,其中包含一个名为CheckRule()
的方法,该方法将更新您的消息并返回一个bool
。 然后,您将为要测试的每个规则创建一个接口实现,并将该类添加到List<ITestRule>
对象。 从上面的Redmondo示例中,我将更改为以下内容:
var discountRules =
new List<ITestRule>
{
new TestPartA(),
new TestPartB(),
new TestPartC(),
new TestPartD(),
};
然后,您将新的List<ITestRule>
传递给一个求值器,它将循环遍历每个类并运行CheckRule()
方法。
我试图坚持一个称为“快速失败”的原则; 方法应该在它们应该发生时失败,并立即返回错误的详细信息。 然后调用方法适当地响应(将异常重新抛出给它的调用者,记录细节,如果它是一个UI绑定方法则显示错误等): -
http://en.wikipedia.org/wiki/Fail-fast
但是,这并不意味着使用异常来控制应用程序的流程。 刚养的时候,你可以对付它通常是不好的做法异常: -
http://msdn.microsoft.com/en-us/library/dd264997.aspx
在你的情况下,我会重新编写你的代码(例如): -
private bool SomeMethod()
{
bool success = false;
try
{
TestPartA();
TestPartB();
TestPartC();
TestPartD();
success = true;
}
catch (Exception ex)
{
LogError(ex.Message);
}
//... some further tests: display the error message somehow, then:
return success;
}
private void TestPartA()
{
// Do some testing...
if (somethingBadHappens)
{
throw new ApplicationException("The error that happens");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.