在多个点抛出异常(重构)
本文关键字:重构 抛出异常 | 更新日期: 2023-09-27 18:18:27
我正在编写一个函数,它接受用户输入,在我们的数据库中运行一个过程,并比较值。在此过程中,我需要检查我们是否收到了正确的输入,然后检查查询是否返回了一个可接受的值。
private void DoTheThing(int? userInput1, int? userInput2, int valuePassedIn)
{
if (userInput1 == null || userInput2 == null)
{
Exception ex = new Exception();
ex.Data.Add("Message", "You screwed up.");
throw ex;
}
var queryResult = 0; //execute a query using the non-null inputs
if (queryResult == null) //or otherwise doesn't return an acceptable value
{
Exception ex = new Exception();
ex.Data.Add("Message", "some other thing happened");
throw ex;
}
else
{
//We're good, so do the thing
}
}
关于这一点的一个快速注释:我意识到反对异常作为流控制的争论,我最好在我走到这里之前检查用户的输入。我不会讨论所有的细节,但是请接受我这样写函数有点卡住了。话虽如此,我的问题是:
考虑到这里两个异常之间的唯一区别是消息和它们被抛出的时间,我如何才能将此代码清理为DRY并避免在确定将成为问题后运行不必要的代码?
我想过使用goto
并将错误代码放在那里,但这实际上只会移动问题。如果我将异常代码移到底部并检查message
变量(或类似的东西),那么我只是在运行不需要首先运行的代码。
我建议不要扔Exception
(这意味着出了问题,没有可用的评论),但ArgumentNullException
和InvalidOperationException
类。另一个修改是避免箭头反模式:
private void DoTheThing(int? userInput1, int? userInput2, int valuePassedIn)
{
// What actually went wrong? An argument "userInput1" is null
if (null == userInput1)
throw new ArgumentNullException("userInput1");
else if (null == userInput2)
throw new ArgumentNullException("userInput2"); // ...or userInput2 is null
var queryResult = executeSomeQuery(userInput1, userInput2, valuePassedIn);
// What went wrong? We don't expect that null can be returned;
// so the operation "executeSomeQuery" failed:
// we've provided validated (not null) values and got unexpected return.
// Let it have been known.
if (null == queryResult)
throw new InvalidOperationException(
String.Format("Query ({0}, {1}, {2}) returned null when bla-bla-bla expected",
userInput1, userInput2, valuePassedIn));
// We're good, so do the thing
// Note that's there's no "arrow-head antipattern":
// we're not within any "if" or "else" scope
}
编辑:由于每个*Exception
都继承自Exception
,因此可以将一些信息放入Data
:
Exception ex = new ArgumentNullException("userInput1");
ex.Data.Add("Some key", "Some value");
throw ex;
但通常Message
是一个更好的地方来解释发生了什么。
您最好创建一个BadInputException类和一个NullQueryResultException类。它们做两件不同的事情,抛出一个特定的异常比抛出一个泛型异常(…)要好。事实上,我认为FXCop或Visual Studio的代码分析会给你一个抛出泛型异常的警告。
其实没有那么多新代码要写。
public class BadInputException : Exception
{
public BadInputException()
{
this.Data.Add("Message", "You screwed up.")
}
}
然后:
Exception ex = new Exception();
ex.Data.Add("Message", "You screwed up.");
throw ex;
这样做:
throw new BadInputException();
编辑:将"You screw up"消息从message属性移动到Data集合,以匹配OP想要的内容。
我将创建一个方法:
private void CheckResult(bool cond, string msg, string info) {
if (!cond)
return;
Exception ex = new Exception();
ex.Data.Add(msg, info);
throw ex;
}
和call
CheckResult(userInput1 == null || userInput2 == null, "Message", "You screwed up.");
和
CheckResult(queryResult == null, "Message", "You screwed up.");
我认为QuestionRefactoring Guard子句对你很有帮助。
在用保护子句替换嵌套条件中对此有一些说明。
希望对大家有用