Jos*_*off 2 .net domain-driven-design
我的许多应用程序服务层方法都是这样的:
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?
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果客户端为无法找到的实体发出命令,我应该抛出什么类型的异常? MSDN上的InvalidOperationException规范指的是"对象状态"无效.看起来这里并不适用 - 这真的只是一个糟糕的命令.
有什么建议?
我赞成,InvalidOperationException因为这具有语义意义.该状态的Command是糟糕,因为它Id是无效的.
此外,我发现提供.Net Framework的奇偶校验对以后加入项目的开发人员很有帮助.了解Microsoft如何处理类似情况,例如我们发现Enumerable.Single<TSource>或EntityReference<TEntity>.Load使用它们InvalidOperationException.