Many of my application service layer methods go something like this:
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?
}
}
}
What type of exception should I throw if the client has issued a command for an entity that cannot be found? The InvalidOperationException spec on MSDN refers to “object state” not being valid. Seems like that’s not really applicable here – it’s really just a bad command.
Any suggestions?
I would favor
InvalidOperationExceptionas this makes semantic sense. The state of theCommandis bad as itsIdis not valid.Also, I find providing parity with the .Net Framework is helpful for developers who join your project later. Looking to how Microsoft handles similar situations, such as
Enumerable.Single<TSource>orEntityReference<TEntity>.Loadwe find they useInvalidOperationException.