在实体框架中捕获Sql异常4?最佳做法是什么? [英] Catching Sql Exception In Entity Framework4?What is the best practice?

查看:132
本文介绍了在实体框架中捕获Sql异常4?最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您在数据库中使用什么实践来捕获sql异常?
有没有人写了一个通用Sql异常处理程序,他们捕获最常见的错误?



你如何做任何例子?



谢谢

解决方案

仅处理底层的意外异常



您的数据层(在这种情况下为Entity Framework)的异常应仅由您的业务层处理。业务层可以提高(如有必要)为您的表示层(UI)提供更高级别的异常。



不要抛出并捕获多个异常你的应用层。这被认为是不好的做法。表示层只能处理业务层异常。



不要使用以下方式吞下异常:

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

尽可能早地捕获预期的异常



始终尝试处理预期的异常(例如 FileNotFoundException )as尽快如果你可以处理它,直接在那里处理它。如果没有,请重新抛出自定义异常,并将其处理在您的底层



重新抛出异常时不要清除堆栈跟踪



隐藏并重新抛出(see)

  try {} catch(Exception){throw; 

而不明确



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


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

解决方案

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; }

这篇关于在实体框架中捕获Sql异常4?最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆