Skip to content

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

Closed

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));

Activity

  1. added
    untriaged
    on Feb 27, 2026
  2. dotnet-policy-service commented on Feb 27, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-text-json
    See info in area-owners.md if you want to be subscribed.

  3. added a commit that references this issue on Mar 16, 2026
    85b61ab
  4. removed
    untriaged
    on Mar 16, 2026
  5. locked and limited conversation to collaborators on Apr 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions