Skip to content

Commit

Permalink
Slightly better exception types in 4STJ (#134)
Browse files Browse the repository at this point in the history
* Slightly better exception types in 4STJ
* Add new test, fix existing test, throw better exception.
  • Loading branch information
airbreather authored Sep 15, 2023
1 parent 448bf39 commit 7c71c8c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using NetTopologySuite.Features;
Expand Down Expand Up @@ -107,7 +108,12 @@ public override IFeature Read(ref Utf8JsonReader reader, Type objectType, JsonSe
break;

case JsonTokenType.Number:
throw new NotSupportedException("Number value cannot be boxed as a decimal: " + reader.GetString());
// "number" is technically SUPPOSED to be a float, so even though we
// prefer reading it as a decimal, it should at least be safe enough
// to use GetDouble() for the exception message, and certainly safer
// than GetString() which an older version of this code used to use,
// which ALWAYS throws for Number tokens (airbreather 2023-09-14).
throw new JsonException("Number value cannot be boxed as a decimal: " + reader.GetDouble());

case JsonTokenType.String:
feature.Id = reader.GetString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,8 @@ public override Geometry Read(ref Utf8JsonReader reader, Type typeToConvert, Jso
geometry = _geometryFactory.CreateGeometryCollection(geometries ?? new Geometry[0]);
break;
default:
throw new NotSupportedException();
// satisfy the compiler, but this is impossible today (airbreather 2023-09-14)
throw new JsonException();
}

return geometry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,25 @@ public void TestFeatureIdSerializedToRoot()
};

string expected = "{\"type\":\"Feature\",\"id\":1,\"geometry\":{\"type\":\"Point\",\"coordinates\":[0,0]},\"properties\":{\"name\":\"Test feature\"}}";
Assert.That(expected, Is.EqualTo(expected));
Assert.That(JsonSerializer.Serialize(feature, options), Is.EqualTo(expected));
}

[GeoJsonIssueNumber(132)]
[Test]
public void TestNumericFeatureIdMustBeValidDecimal()
{
string serialized = $@"
{{
""type"": ""Feature"",
""id"": {double.MaxValue},
""geometry"": {{
""type"": ""Point"",
""coordinates"": [0, 0]
}}
}}
";

Assert.That(() => JsonSerializer.Deserialize<Feature>(serialized, DefaultOptions), Throws.InstanceOf<JsonException>());
}
}
}

0 comments on commit 7c71c8c

Please sign in to comment.