【问题标题】:Handling SQL Server errors separately from other types of exceptions将 SQL Server 错误与其他类型的异常分开处理
【发布时间】:2019-12-15 08:51:45
【问题描述】:

我在我的 ASP.NET MVC Rest API 项目中使用 ADO.NET 和 Entity Framework。我需要知道是否要捕获所有与 SQL 和 DB 相关的异常,是否足以处理 SqlException 类型的异常或 DB 可能会抛出其他类型的异常?

这是一个示例,我想在其中捕获与其他类型的与数据库无关的异常不同的数据库错误。

try
{
    using (SqlConnection sqlConnection = new SqlConnection(Settings.connectionString))
    {
        SqlCommand command = new SqlCommand(sqlQuery, sqlConnection);
        SqlParameter p = command.Parameters.Add(STRUCTURED_DATA_TABLE_NAME, SqlDbType.Structured);
        p.Value = dataTable;
        p.TypeName = TYPE_NAME;
        sqlConnection.Open();
        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    keys.Add(reader.GetInt32(i));
                }
            }
        }
        else
        {
        }

        sqlConnection.Close();
    }

    return new StatusResponseKeysList
    {
        keysList = keys,
        ErrorCode = ErrorCodes.ERROR_CODE_000
    };
}
catch (Exception e)
{
    if (e.GetType() == typeof(SqlException))
    {
        //this is a db error
    }
    else
    {
        //this is not a db error
    }
}

【问题讨论】:

    标签: c# entity-framework exception ado.net sqlexception


    【解决方案1】:

    由于 EF 允许 SqlException 从底层数据库驱动程序冒泡,因此假设确实捕获 SqlException 就足够了。

    但正因如此,许多数据库相关异常(如 SqlException、OdbcException 等)的基本类型是 DbException,您可能会认为捕获 DbException 更好。

    顺便说一句,像这样捕捉会更好一点:

    try
    {
        // Some database-related activities that might throw errors
    }
    catch (SqlException e) 
    {
        // SqlException
    }
    catch (DbException e)
    {
        // DbException
    }
    catch (Exception e)
    {
        // Exception
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-04
      • 2016-04-11
      • 2010-09-10
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      相关资源
      最近更新 更多