Skip to content

Include propertyName when KeyNotFoundException is thrown in JsonElement.GetProperty #124956

@FireAlkazar

Description

@FireAlkazar

Suggestion

Add property name in exception message when KeyNotFoundException is thrown:
https://github.com/dotnet/runtime/blob/main/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs#L142

Current behavior

No property can be found in logs.

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
   at System.Text.Json.JsonElement.GetProperty(String propertyName)
   at ...

Proposed behavior

Property name can be found in logs.

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary. Property name is 'dateRange'.
   at System.Text.Json.JsonElement.GetProperty(String propertyName)
   at ...

Reasoning

When having chained methods sometimes it is hard to understand what property caused the issue.
Sample code:

var dateEnd = jsonElement.EnumerateArray()
    .First()
    .GetProperty("periods")
    .EnumerateArray()
    .First()
    .GetProperty(“dateRange”)
    .GetProperty("dateEnd")
    .GetDateTime()
    .Date;

Proposed implementation

// Strings.KeyNotFoundException = "The given key was not present in the dictionary. Property name is '{0}'."
throw new KeyNotFoundException(SR.Format(Strings.KeyNotFoundException, propertyName));

Metadata

Metadata

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions