diff --git a/GFramework.Game.Tests/Serializer/JsonSerializerTests.cs b/GFramework.Game.Tests/Serializer/JsonSerializerTests.cs index 1fe1a59e..b6eb1a49 100644 --- a/GFramework.Game.Tests/Serializer/JsonSerializerTests.cs +++ b/GFramework.Game.Tests/Serializer/JsonSerializerTests.cs @@ -82,6 +82,23 @@ public sealed class JsonSerializerTests }); } + [Test] + public void Deserialize_With_Runtime_Type_Should_Throw_With_Target_Type_Context_When_Json_Is_Invalid() + { + var serializer = new GameJsonSerializer(); + + var exception = + Assert.Throws(() => + serializer.Deserialize("{invalid json}", typeof(PlayerStateStub))); + + Assert.Multiple(() => + { + Assert.That(exception, Is.Not.Null); + Assert.That(exception!.Message, Does.Contain(typeof(PlayerStateStub).FullName)); + Assert.That(exception.InnerException, Is.Not.Null); + }); + } + [Test] public void Deserialize_With_Runtime_Type_Should_Return_Target_Runtime_Type() { diff --git a/GFramework.Game/Serializer/JsonSerializer.cs b/GFramework.Game/Serializer/JsonSerializer.cs index d246f95b..3e498840 100644 --- a/GFramework.Game/Serializer/JsonSerializer.cs +++ b/GFramework.Game/Serializer/JsonSerializer.cs @@ -67,7 +67,7 @@ public sealed class JsonSerializer return (T)DeserializeCore( data, typeof(T), - static (json, type, settings) => JsonConvert.DeserializeObject(json, settings)); + static (json, _, settings) => JsonConvert.DeserializeObject(json, settings)); } /// @@ -94,22 +94,25 @@ public sealed class JsonSerializer ArgumentNullException.ThrowIfNull(targetType); ArgumentNullException.ThrowIfNull(deserialize); + object? result; + try { - var result = deserialize(data, targetType, _settings); - if (result == null) - { - throw new InvalidOperationException( - $"Deserialization returned null for target type '{targetType.FullName}'."); - } - - return result; + result = deserialize(data, targetType, _settings); } - catch (Exception ex) when (ex is InvalidCastException) + catch (Exception ex) when (ex is not ArgumentException) { throw new InvalidOperationException( $"Failed to deserialize JSON to target type '{targetType.FullName}'.", ex); } + + if (result == null) + { + throw new InvalidOperationException( + $"Deserialization returned null for target type '{targetType.FullName}'."); + } + + return result; } } \ No newline at end of file