实体框架中的异常处理,具有存储库模式的 MVC
我在我的项目中使用实体框架,并以 MVC 作为前端,并使用存储库实现了工作单元模式> 图案。
我在存储库之上有服务层来处理业务。
我的问题是在哪里处理异常?
将所有异常传递到表示层并在控制器中处理它是个好主意还是我需要在底层?
I am using entity framework for my project with MVC as front end and I have implemented unit of work pattern with repository pattern.
I have service layer on top of repositories to handle business.
My question is where to handle exceptions?
Is it good idea to let pass through all exceptions to presentation layer and handle it in the controller or do I need to handle it in the bottom layers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,总的想法是不要让 UI 处理所有异常,这也没有多大意义。假设您有一个使用 ADO.NET 实现的数据层。这里的一般模式是在数据层中处理 SqlException,然后将 SqlException 包装在上层应该处理的更有意义的 DatabaseLayerException 中 - 并且您一直遵循此模式直到顶部,因此您可以拥有类似 InfrastructureException、ApplicationException 等内容...
在最顶层,您捕获所有未处理的 ApplicationException(并且您使所有异常都继承这个异常以实现多态性),并且捕获所有未处理的异常作为不太可能发生的特殊情况,并尝试从中恢复。
我还建议使用日志记录,无论是手动还是通过 AOP - 您会在网上找到大量资源(也许是 Log4Net ?)。
Well, the general idea is not to let UI handle all exceptions, nor that makes much sense. Lets say you have a data layer implemented with ADO.NET. The general pattern here is to handle SqlExceptions in data layer, and then wrap the SqlException in a more meaningfull DatabaseLayerException that upper layers should handle - and you follow this pattern all the way to the top, so you can have something like InfrastructureException, ApplicationException etc...
On the very top, you catch all ApplicationExceptions that went unhandled (and you make all your exceptions inherit this one for polymorphism), and you catch all unhandled Exceptions as a special case not likely to happen, and try to recover from it.
I also suggest use of logging, either manually or with AOP - you will find plenty of resources online (perhaps Log4Net ?).
我认为在任何异常处理策略中,您都有以下选择:
throw;
或throw new Exception("message", InnerException);
。最后,还有一些全局选项,用于将异常记录为某种日志格式,或者发送电子邮件等。我没有将其包含在上述三个选项中,因为这对于上述所有三个选项来说都是全局的。
话虽如此,我认为在上述应用程序的每一层,您都必须问自己可以通过上述三种方式中的哪一种来处理异常。如果您无法从中恢复或忽略它,那么您应该将其向上冒泡到一个友好的错误页面,您可以在其中进行最终的清理和异常的呈现。
I think in any exception handeling strategy you have these options:
throw;
orthrow new Exception("message", InnerException);
to name a few.Lastly there are the global options to log the exception to some log format, or to send an email, etc. I don't include this in the above three options, because this is global to all the above three options.
So having said that I think that at each layer in your application described above you have to ask your self in which of the above three ways can you handle the exception. If you can not recover from it or ignore it, then you should bubble it upwards to a friendly error page where you do final cleaning up and presentation of the exception.