我的许多应用程序服务层方法都是这样的:
public class Command
{
public int Id { get; private set; }
}
public class Repository
{
public Entity Load(int id)
{
// the usual stuff here
}
}
public class AppService
{
public void Execute(Command command)
{
var entity = new Repository().Load(command.Id);
if (entity == null)
{
// what type of exception do I throw here?
}
}
}
如果客户端向无法找到的实体发出命令,我应该抛出什么类型的异常? The InvalidOperationException spec on MSDN指“对象状态”无效。似乎这并不真正适用于此 - 这实际上只是一个错误的命令。
有什么建议吗?
最佳答案
我赞成InvalidOperationException
因为这具有语义意义。 Command
的状态很糟糕,因为它的 Id
无效。
此外,我发现提供与 .Net Framework 的同等功能对于稍后加入您的项目的开发人员很有帮助。看看微软如何处理类似的情况,例如 Enumerable.Single<TSource>
或 EntityReference<TEntity>.Load
我们发现他们使用InvalidOperationException
.
关于.net - 当对找不到的实体发出命令时,适当的 .NET 异常类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6655164/