尝试在存储库中捕获
我看过的存储库模式示例均不包含任何类型的错误处理。 这是为什么呢?举例来说,我有这样的情况:
public virtual TItem Insert<TItem>(TItem item) where TItem:class,new()
{
dbContext.Set<TItem>().Add(item);
try
{
dbContext.SaveChanges();
}
catch (DbUpdateException)
{
return null;
}
return item;
}
我们违反约束的实例。我捕获了 DbUpdateException...如果不在存储库本身中,此错误处理将在哪里进行?
None of the examples I have looked at for Repository Patterns include any kind of error handling.
Why is this? Say for instance I have this:
public virtual TItem Insert<TItem>(TItem item) where TItem:class,new()
{
dbContext.Set<TItem>().Add(item);
try
{
dbContext.SaveChanges();
}
catch (DbUpdateException)
{
return null;
}
return item;
}
An instance where we violate a constraint. I catch the DbUpdateException... Where would this error handling live if not in the repository itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在正确设计的系统中,约束永远不能被违反。让您的实体更加智能:例如,不要使用盲目的自动实现的设置器。
存储库不是进行数据验证的地方。正确的位置是:
唯一出现这些异常的情况是当您运行
单元集成测试并且出现故障时,这将表明您的数据库约束与您的实体不匹配,或者您的实体实现不正确。所以你绝对不应该抓住
它们。In a properly-designed system, the constraints should never be able to be violated. Make your entities smarter: don't use blind auto-implemented setters, for example.
The repository is not the place to do data validation. The proper place is:
The only time these exceptions should come up is when you run your
unitintegration tests and you get a failure, which will reveal that either your database constraints are mismatched with your entity, or your entity is implemented incorrectly. So you definitely shouldn'tcatch
them.在大多数情况下,存储库不需要担心处理异常。使用存储库的类应该处理这个问题。在您的示例中,如果发生插入错误,为什么要返回 null?这不是比抛出异常更不清楚吗?
例如,假设我们要通过存储库插入一条记录,然后打印出新的 ID。假设插入由于任何原因将失败。
按照问题中的模式,如果
Insert
失败,您会在第二行收到NullReference
异常。这有点奇怪。看到第一行的DbUpdateException
就更清楚了。最好能够指望Insert
始终返回有效实例或抛出异常。For the most part, a repository doesn't need to worry about handling exceptions. The classes that are consuming the repositories should handle that. In your example, why would want to return null if an insert error occurs? Isn't that less clear than just throwing an exception?
For example, let's say we want to insert a record through the repository and then print out the new ID. Assume that the insert is going to fail for any reason.
Following the pattern in your question, you'd get a
NullReference
exception on the second line if theInsert
fails. That's a little strange. It's more clear to see theDbUpdateException
on the first line. It's also better to be able to count onInsert
always either returning a valid instance or throwing an exception.