Reputation: 10375
I'm using ADO.NET and Entity Framework in my ASP.NET MVC Rest API project. I need to know if I want to catch all SQL and DB-related exceptions, is it enough to handle exception of type SqlException
or DB may throw other types of exception?
Here is a sample where I want to catch database errors differently from other types of exceptions which are not related to database.
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
}
}
Upvotes: 0
Views: 603
Reputation: 3177
Since EF allows SqlException to bubble up from the underlying database driver, you are correct to assume that indeed catching SqlException is enough.
But for the sake of it, the base type of many database-related exceptions like SqlException, OdbcException, etc, is DbException you might argue that catching DbException is better.
And by the way, it's a little bit nicer to catch like this:
try
{
// Some database-related activities that might throw errors
}
catch (SqlException e)
{
// SqlException
}
catch (DbException e)
{
// DbException
}
catch (Exception e)
{
// Exception
}
Upvotes: 2