在C#Catch异常子句中调用另一个数据库的SQL过程
问题描述:
除了记录SqlException之外,我还试图调用另一个存储最初发生错误的内容的数据库。但是,我得到SqlConnection部分的警告'Unreachable code detected',它肯定没有执行我试图运行的过程。在C#Catch异常子句中调用另一个数据库的SQL过程
catch (SqlException ex)
{
throw new DataException(ex.Message, ex);
//Call Error Management DB Connection and add content to the table
using (SqlConnection connection = new SqlConnection(_errorManagementConnectionString))
{
SqlCommand cmd = new SqlCommand("[dbo].[InsertDataErrors]", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@InputParam", InputParam);
cmd.Parameters.AddWithValue("@Content", Content);
cmd.ExecuteNonQuery();
connection.Open();
}
}
我该如何解决这个错误,并确保SqlException与我尝试运行的过程一起记录?
答
您需要在catch
块的末尾抛出异常。
如果您担心失败,您也可以将using
语句包装在另一个try/catch中。
另外,您需要在执行SqlCommand
之前打开连接。这就是为什么你的DataException
没有被抛出,另一个未处理的异常是在你的代码到达该行之前抛出。
例如为:
catch (SqlException ex)
{
try
{
//Call Error Management DB Connection and add content to the table
using (SqlConnection connection = new SqlConnection(_errorManagementConnectionString))
{
SqlCommand cmd = new SqlCommand("[dbo].[InsertDataErrors]", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@InputParam", InputParam);
cmd.Parameters.AddWithValue("@Content", Content);
connection.Open();
cmd.ExecuteNonQuery();
}
}
catch
{
// Add any desired handling.
}
throw new DataException(ex.Message, ex);
}
+0
谢谢!添加try-catch子句并在事件查看器中显示异常指出新SQL连接中的错误。 – Dev
答
你需要把扔在块的结尾。
您的错误处理代码失败,这就是为什么您认为它应该在顶部 - 可能是因为您没有像其他地方打开连接。
您还需要捕获当您尝试在数据库中记录错误时发生的可能的异常,因为如果发生第一个数据库错误时会出现失败的情况。
然后你最终得到一个非常混乱的异常处理程序,所以你可能应该将它移动到另一个方法。
// somehting with database ....
}
catch (SqlException ex)
{
AttemptToLogDbError(ex)
throw new DataException(ex.Message, ex);
}
// ...
}
void AttemptToLogDbError(SqlException ex)
{
try
{
//Call Error Management DB Connection and add content to the table
using (SqlConnection connection = new SqlConnection(_errorManagementConnectionString))
{
connection.open();
SqlCommand cmd = new SqlCommand("[dbo].[InsertDataErrors]", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@InputParam", InputParam);
cmd.Parameters.AddWithValue("@Content", Content);
cmd.ExecuteNonQuery();
}
}
catch (Exception err)
{
// OMG nothing is working at all! log/report this somehow, but do not throw
}
}
在'using'部分之前抛出'DataException',所以无法使用。 – MatSnow
我已经尝试了另一种方式,它然后不会抛出新的DataException,如果我把使用事先。 – Dev
你也应该使用['Add'](https://*.com/questions/21110001/sqlcommand-parameters-add-vs-addwithvalue)而不是['AddWithValue'](https://*.com/questions/21110001/SqlCommand的参数加-VS-addwithvalue)。 – MatSnow