In the following code, the connection string password is intentionally incorrect to raise a SqlException when opening a connection.
while (true)
{
try
{
SqlConnection conn = new SqlConnection("Server=localhost;Database=northwind;UID=sa;PWD=b;");
conn.Open();
}
catch (Exception ex)
{
try
{
Console.Write(ex.GetHashCode() + " : ");
ex.Data.Add("MyKey", "LogData");
Console.WriteLine(ex.Message);
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
}
}
Thread.Sleep(500);
}
For logging purposes, I want to add values to the exception data dictionary. After the first exception, I found that most of the subsequent exceptions are the same instance of the SqlException class (checked using GetHashCode ()) and already contains entries in the data dictionary. This throws an ArgumentException due to an already existing key.
34826618 : Login failed for user 'sa'.
34826618 : Item has already been added. Key in dictionary: 'MyKey' Key being added: 'MyKey'
34826618 : Item has already been added. Key in dictionary: 'MyKey' Key being added: 'MyKey'
34826618 : Item has already been added. Key in dictionary: 'MyKey' Key being added: 'MyKey'
, , Data, , , , . , , , , , .
? ?
P.S. , , , , SqlException .