存储库内的异常:如何处理它们?
我有兴趣了解您的想法的一个简单问题:
通过您的存储库实现,您是否喜欢让异常在存储库内抛出并将异常处理留给调用者,或者您更喜欢在存储库内捕获异常,存储异常并返回 false/null?
An easy one that I am interested in getting your thoughts on:
With your repository implementations, do you like to let exceptions be thrown inside the repository and leave the exception handling to the caller, or do you prefer to catch exceptions inside your repository, store the exception and return false/null?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于。
我会让异常冒泡吗? 绝对地。 但我想要这个用于连接失败、命令失败。 无论你做什么,不要只是隐藏这些,你需要了解它们。 我希望我的应用程序尽快失败,以减少副作用和进一步的损害。
我也记录异常。 我使用 Log4net 来帮助解决这个问题。 但我喜欢在源头记录异常。 我会让它们从那里冒出来。
返回空值? 如果找不到某些东西(即通过 id 查找某些东西但它不存在),那么我返回 null,而不是异常。 但在某些情况下,当这种情况发生时,我会看到抛出一个新的异常。
要点:例外应该是“例外”,而不是规则。 如果抛出异常,则应该是因为确实出现了问题,您需要修复它。
It Depends.
Do I let exceptions bubble up? Absolutely. But I want this for connection failure, command failures. Whatever you do, don't just hide these, you need to know about them. I prefer my applications to fail as quickly as possible to reduce side-effects and further damage.
I also log exceptions. I use Log4net to help with this. But I like to log exceptions at the source. I will let them bubble up from there.
Return null? If something cannot be found (i.e. looking for something by id and it isn't there), then I return null, not an exception. But there are cases where I could see throwing a new exception when this happens.
Main point: exceptions should be 'exceptional', not the rule. If an exception is thrown, it should be because something is really wrong and you need to fix it.
我通常会让异常泄漏,但如果我处于特别进取的心情,我会将它们包装在 RepositoryException 中,以防止客户端关心底层存储引擎。
我永远不会返回 false/null 而不是异常,因为这些值背后已经有一个含义。
在极少数情况下,您可能有一个脑死亡的存储引擎,它会在非异常情况下生成异常 - 我会捕获这些特定的异常并在适当的情况下返回 null(例如,如果一行不存在,但存储引擎会抛出异常)在这种情况下出现错误 - 我会捕获它并返回 null)。
I usually let exceptions leak, though if I'm in a particularly Enterprisey mood I'll wrap them in a RepositoryException to keep clients from caring about the underlying storage engine.
I would never return false/null instead of an exception, as there's already a meaning behind those values.
In rare cases, you could have a brain-dead storage engine that generates exceptions on non-exceptional cases - and I would catch those specific ones and return null if appropriate (eg., if a row does not exist, but the storage engine throws an error on that case - I'd catch it and return null).