C#:从其他类型的执行中分别处理SQL Server错误

问题描述 投票:0回答:1

我在ASP.NET MVC Rest API项目中使用ADO.NET和实体框架。我需要知道是否要捕获所有与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个回答
0
投票

由于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
}
© www.soinside.com 2019 - 2024. All rights reserved.