Skip to content

Commit

Permalink
Include key when throwing KeyNotFoundException in indexer (#34759)
Browse files Browse the repository at this point in the history
* Include key when throwing KeyNotFoundException in indexer

* Add quotes around replacement markers to be consistent with other strings
  • Loading branch information
lennartb- committed Apr 10, 2020
1 parent ab6e225 commit f004abe
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
<value>Collection was modified; enumeration operation may not execute.</value>
</data>
<data name="DuplicateKey" xml:space="preserve">
<value>An element with the same key but a different value already exists. Key: {0}</value>
<value>An element with the same key but a different value already exists. Key: '{0}'</value>
</data>
<data name="InvalidEmptyOperation" xml:space="preserve">
<value>This operation does not apply to an empty instance.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ public TValue this[TKey key]
return value;
}

throw new KeyNotFoundException();
throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,15 @@ public void Clear_HasComparer_ReturnsEmptyWithOriginalComparer()
Assert.True(clearedDictionary.ContainsKey("A"));
}

[Fact]
public void Indexer_KeyNotFoundException_ContainsKeyInMessage()
{
var map = ImmutableDictionary.Create<string, string>()
.Add("a", "1").Add("b", "2");
var exception = Assert.Throws<KeyNotFoundException>(() => map["c"]);
Assert.Contains("'c'", exception.Message);
}

protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableDictionaryTest.Empty<TKey, TValue>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,15 @@ public void ValueRef_NonExistentKey()
Assert.Throws<KeyNotFoundException>(() => dictionary.ValueRef("c"));
}

[Fact]
public void Indexer_KeyNotFoundException_ContainsKeyInMessage()
{
var map = ImmutableSortedDictionary.Create<string, string>()
.Add("a", "1").Add("b", "2");
var exception = Assert.Throws<KeyNotFoundException>(() => map["c"]);
Assert.Contains("'c'", exception.Message);
}

protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableSortedDictionaryTest.Empty<TKey, TValue>();
Expand Down

0 comments on commit f004abe

Please sign in to comment.