Catching Sql Exception In Entity Framework4?What is the best practice?

雨燕双飞 提交于 2019-12-23 12:56:12

问题


What practices do you use in your datalayer to catch sql exceptions? Has anybody written a Generic Sql Exception handler where they catch the most common errors ?

how do you do it any examples out there?

Thanks


回答1:


Handle unexpected exception by the underlying layer only

Exceptions from your data layer (in this case Entity Framework) should be handled only by your business layer. The business layer can raise then (if necessary) a more high-level exception for your presentation layer (UI).

Don't throw and catch exceptions across more than one layer of your application. This is considered to be bad practice. The presentation layer should only handle business layer exceptions.

Never swallow exceptions by using:

try {} catch (Exception) { // who cares }

Catch expected exceptions as early as possible

Always try to handle expected exceptions (e.g. FileNotFoundException) as soon as possible. If you can handle it, handle it directly there. If not, re-throw a Custom Exception and handle it in your underlying layer.

Don't clear the stack trace when re-throwing an exception

Catch and re-throw implicitly (see)

try {} catch (Exception) { throw; }

and not explicitly

try {} catch (Exception ex) { throw ex; }



来源:https://stackoverflow.com/questions/4323439/catching-sql-exception-in-entity-framework4what-is-the-best-practice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!