Today, I saw some code that looked like the classic “I can’t recreate this bug, so I’ll write some code to log extra information, and I’ll hope this somehow helps me diagnose the issue”.
They had a list of data, and the ID in this list should be unique, but it was in there twice due to a bug. So it would look like something like this (ID =1 is in there twice):
private List<Code> _codes = new List<Code>()
{
new Code
{
IsSelectable = true,
ID = 1
},
new Code
{
IsSelectable = true,
ID = 1
},
new Code
{
IsSelectable = false,
ID = 2
},
new Code
{
IsSelectable = true,
ID = 3
}
};
Then their method contained this code to validate the data:
private void EnsureValid(int idToFind)
{
try
{
_codes.Single(s => s.ID == idToFind);
}
catch (InvalidOperationException)
{
Dictionary<string, object> customData = new Dictionary<string, object>
{
{ "ID", _codes.ToDictionary(x=>x.ID) }
};
LogToErrorDB(customData);
}
}
The Single will throw an exception due to there being more than one matching element (Single will succeed when there is a Single match). In the catch block, they then convert the code list to a dictionary and will log this in the error database. However, a dictionary requires the keys in the dictionary to be unique. Since there’s duplicate IDs, this will throw an exception again, this time with:
“System.ArgumentException: ‘An item with the same key has already been added.'”
Error thrown in the catch block
So you get an error whilst trying to log your error. The extra information they intended to log is never logged.
I’ve seen this mistake happen a few times before, and usually you can test it by artificially creating the data condition. Then they would realise their error logging doesn’t work.