Catching Sql Exception In Entity Framework4?What is the best practice?
What practices do you use in your datalayer to catch sql exceptions? Has anybody written a Generic Sql Exceptio开发者_如何学编程n handler where they catch the most common errors ?
how do you do it any examples out there?
Thanks
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; }
精彩评论