Improve error message in the new `JsonNode.GetElementIndex()` and `GetPropertyName...
authorEirik Tsarpalis <eirik.tsarpalis@gmail.com>
Mon, 14 Aug 2023 13:22:38 +0000 (16:22 +0300)
committerGitHub <noreply@github.com>
Mon, 14 Aug 2023 13:22:38 +0000 (14:22 +0100)
src/libraries/System.Text.Json/src/Resources/Strings.resx
src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonNode.cs
src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.Node.cs

index 83468d9..f091984 100644 (file)
   <data name="NodeWrongType" xml:space="preserve">
     <value>The node must be of type '{0}'.</value>
   </data>
+  <data name="NodeParentWrongType" xml:space="preserve">
+    <value>The node must have a parent node of type '{0}'.</value>
+  </data>
   <data name="NodeDuplicateKey" xml:space="preserve">
     <value>An item with the same key has already been added. Key: {0}</value>
   </data>
index a920469..a06fc47 100644 (file)
@@ -261,14 +261,14 @@ namespace System.Text.Json.Nodes
         /// </exception>
         public string GetPropertyName()
         {
-            JsonObject? jsonObject = _parent as JsonObject;
+            JsonObject? parentObject = _parent as JsonObject;
 
-            if (jsonObject is null)
+            if (parentObject is null)
             {
-                ThrowHelper.ThrowInvalidOperationException_NodeWrongType(nameof(JsonObject));
+                ThrowHelper.ThrowInvalidOperationException_NodeParentWrongType(nameof(JsonObject));
             }
 
-            return jsonObject.GetPropertyName(this);
+            return parentObject.GetPropertyName(this);
         }
 
         /// <summary>
@@ -279,14 +279,14 @@ namespace System.Text.Json.Nodes
         /// </exception>
         public int GetElementIndex()
         {
-            JsonArray? jsonArray = _parent as JsonArray;
+            JsonArray? parentArray = _parent as JsonArray;
 
-            if (jsonArray is null)
+            if (parentArray is null)
             {
-                ThrowHelper.ThrowInvalidOperationException_NodeWrongType(nameof(JsonArray));
+                ThrowHelper.ThrowInvalidOperationException_NodeParentWrongType(nameof(JsonArray));
             }
 
-            return jsonArray.GetElementIndex(this);
+            return parentArray.GetElementIndex(this);
         }
 
         /// <summary>
index de1aa75..4391ef8 100644 (file)
@@ -50,6 +50,12 @@ namespace System.Text.Json
             throw new InvalidOperationException(SR.Format(SR.NodeWrongType, typeName));
         }
 
+        [DoesNotReturn]
+        public static void ThrowInvalidOperationException_NodeParentWrongType(string typeName)
+        {
+            throw new InvalidOperationException(SR.Format(SR.NodeParentWrongType, typeName));
+        }
+
         public static NotSupportedException GetNotSupportedException_CollectionIsReadOnly()
         {
             return new NotSupportedException(SR.CollectionIsReadOnly);