尝试捕获每个数据库连接? [英] try-catch every db connection?

查看:101
本文介绍了尝试捕获每个数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否建议在打开数据库连接的每个函数中放置一个try-catch块,并在那里记录错误,还是应该在应用程序的较高层捕获错误?

  public static类别GetCategoryByName(string name)
{
类别结果;
尝试
{
using(IDbConnection conn = ConnectionHelper.CreateDbConnectionByName(_connectionStringName))
{
conn.Open();
using(IDbCommand cmd = conn.CreateCommand())
{
// do stuff
}
}
}
catch(异常e)
{
//日志错误在这里?
}
返回结果;
}

或者

  try 
{
类别myCat = DataTools.GetCategoryByName(myCat);
//其他东西
}
catch(异常e)
{
//日志错误在这里?
}

总结一下:应该尽快在代码中捕获错误?或者我应该抓住他们有关上下文的更多信息?

解决方案

一如往常,这取决于,只能捕获一个例外,如果你可以做一些事情,或者你有特定的代码(例如重试)发生,否则,让异常起泡,最顶层可以以集中的方式登录/处理它。 / p>

任何其他方式都会导致许多日志记录代码散布着所有的业务逻辑。


Is it recommended to put a try-catch block in every function that opens a DB connection and log the error there, or should I rather catch errors in a higher layer of the application?

public static Category GetCategoryByName(string name)
{
    Category result;
    try
    {
        using (IDbConnection conn = ConnectionHelper.CreateDbConnectionByName(_connectionStringName))
        {
            conn.Open();
            using (IDbCommand cmd = conn.CreateCommand())
            {
                //do stuff
            }
        }
    }
    catch(Exception e)
    {
         // log error here?
    }
    return result;
}

or rather

try
{
    Category myCat = DataTools.GetCategoryByName("myCat");
    // other stuff
}
catch(Exception e)
{
   // log error here?
}

To sum it up: Should errors be caught as early as possible in the code? Or should I rather catch them where I have more information about the context?

解决方案

As always, it depends, but in general, only catch an exception if you can do something about it, or you have specific code (e.g. a retry) to happen, otherwise, let the exception bubble up and the top most layer can log it/deal with it in a centralised fashion.

Any other way results in a lot of logging code interspersed with all the business logic.

这篇关于尝试捕获每个数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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