开发者

Exception handling in entity framework, MVC with repository pattern

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开发者_C百科 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?


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 ?).


I think in any exception handeling strategy you have these options:

  • to recover from the exception if possible (for instance server is down, wait a while and try again)
  • Ignore the exception because it's not serious enough or whatever other reasons.
  • Bubble it upwards. Multiple strategies exist here, such as just a throw; or throw 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜