In the following code the connection string password is intentionally incorrect to cause a SqlException on opening the 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's Data dictionary. After the first exception, I find that most subsequent exceptions are the exact same instance of the SqlException class (verified with GetHashCode()) and already have my Data dictionary entries. This causes a ArgumentException to be thrown due to the key already existing.
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'
I realize that I can change it to use the keyed setter on the Data property, which would add or replace the entry, but my concern is that reuse could result in invalid Data entries being logged. Also, it seems odd that an exception being thrown from a new code execution would be the same instance as a previous exception thrown.
Any insight? Can you reproduce this?
P.S. If you don't think adding entries to the Exception's Data dictionary is appropriate, I'd be glad to hear your thoughts, but it doesn't change the core of the question about why the SqlException instance is being reused.