【发布时间】: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