在 C# 捕获异常子句中为另一个数据库调用 SQL 过程



除了记录 SqlException 之外,我还尝试调用另一个数据库,该数据库存储最初发生错误的内容。但是,我收到 SqlConnection 部分的警告"检测到无法访问的代码",它肯定没有执行我尝试运行的过程。

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);
}

你需要把投掷放在块的末尾。

您的错误处理代码失败,这就是为什么您认为它应该位于顶部 - 可能是因为您没有像其他地方那样打开连接。

您还需要捕获尝试在数据库中记录错误时可能发生的异常,因为在许多情况下,如果发生第一个数据库错误,这将失败。

然后你最终会得到一个非常混乱的异常处理程序,所以你可能应该把它移到另一个方法上。

           // 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
      }
 }