diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f2464ee0f..5312c64e7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - NOTE: This can affect grouping. You can keep the original behavior by setting the option `KeepAggregateException` to `true`. - Serialize stack frame addresses as strings. ([#1692](https://github.com/getsentry/sentry-dotnet/pull/1692)) - Improve serialization perf and fix memory leak in `SentryEvent` ([#1693](https://github.com/getsentry/sentry-dotnet/pull/1693)) +- Add type checking in contexts TryGetValue ([#1700](https://github.com/getsentry/sentry-dotnet/pull/1700)) ### Features diff --git a/src/Sentry/Internal/Extensions/CollectionsExtensions.cs b/src/Sentry/Internal/Extensions/CollectionsExtensions.cs index c07f044cd2..bfdc9afae0 100644 --- a/src/Sentry/Internal/Extensions/CollectionsExtensions.cs +++ b/src/Sentry/Internal/Extensions/CollectionsExtensions.cs @@ -10,7 +10,16 @@ public static TValue GetOrCreate( this ConcurrentDictionary dictionary, string key) where TValue : class, new() - => (TValue)dictionary.GetOrAdd(key, _ => new TValue()); + { + var value = dictionary.GetOrAdd(key, _ => new TValue()); + + if (value is TValue casted) + { + return casted; + } + + throw new($"Expected a type of {typeof(TValue)} to exist for the key '{key}'. Instead found a {value.GetType()}. The likely cause of this is that the value for '{key}' has been incorrectly set to an instance of a different type."); + } public static void TryCopyTo(this IDictionary from, IDictionary to) where TKey : notnull diff --git a/test/Sentry.Tests/Internals/CollectionExtensionsTests.GetOrCreate_invalid_type.verified.txt b/test/Sentry.Tests/Internals/CollectionExtensionsTests.GetOrCreate_invalid_type.verified.txt new file mode 100644 index 0000000000..f448fd5bc1 --- /dev/null +++ b/test/Sentry.Tests/Internals/CollectionExtensionsTests.GetOrCreate_invalid_type.verified.txt @@ -0,0 +1,4 @@ +{ + Type: Exception, + Message: Expected a type of CollectionExtensionsTests+Value to exist for the key 'key'. Instead found a System.Int32. The likely cause of this is that the value for 'key' has been incorrectly set to an instance of a different type. +} \ No newline at end of file diff --git a/test/Sentry.Tests/Internals/CollectionExtensionsTests.cs b/test/Sentry.Tests/Internals/CollectionExtensionsTests.cs new file mode 100644 index 0000000000..d2557a0cc0 --- /dev/null +++ b/test/Sentry.Tests/Internals/CollectionExtensionsTests.cs @@ -0,0 +1,16 @@ +using System.Collections.Concurrent; + +[UsesVerify] +public class CollectionExtensionsTests +{ + [Fact] + public Task GetOrCreate_invalid_type() + { + var dictionary = new ConcurrentDictionary {["key"] = 1}; + return Throws(() => dictionary.GetOrCreate("key")).IgnoreStackTrack(); + } + + class Value + { + } +}