Skip to content

Commit

Permalink
Handle TargetInvocationException when reading a property as an error …
Browse files Browse the repository at this point in the history
…message string
  • Loading branch information
alexeykuptsov committed Dec 24, 2023
1 parent 8472305 commit b31ee5b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
5 changes: 5 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,11 @@ public class DefaultsExample
public string Value { get; set; }
}

public class ThrowingPropertyExample
{
public string Value => throw new InvalidOperationException();
}

public class CustomGenericDictionary : IDictionary<string, string>
{
private readonly Dictionary<string, string> dictionary = new Dictionary<string, string>();
Expand Down
13 changes: 13 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,19 @@ public void SerializationEmitsPropertyWhenValueDifferFromDefaultValueAttribute()

serialized.Should().Contain("Value");
}

[Fact]
public void SerializationHandlesThrowingProperties()
{
var writer = new StringWriter();
var obj = new ThrowingPropertyExample();

Serializer.Serialize(writer, obj);
var serialized = writer.ToString();

serialized.Should()
.Be("Value: Exception of type System.InvalidOperationException was thrown\r\n".NormalizeNewLines());
}

[Fact]
public void SerializingAGenericDictionaryShouldNotThrowTargetException()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,17 @@ public void Write(object target, object? value)

public IObjectDescriptor Read(object target)
{
var propertyValue = propertyInfo.ReadValue(target);
object? propertyValue;
try
{
propertyValue = propertyInfo.ReadValue(target);
}
catch (TargetInvocationException e)
{
return new ObjectDescriptor(
$"Exception of type {e.InnerException!.GetType().FullName} was thrown",
typeof(string), typeof(string), ScalarStyle.Any);
}
var actualType = TypeOverride ?? typeResolver.Resolve(Type, propertyValue);
return new ObjectDescriptor(propertyValue, actualType, Type, ScalarStyle);
}
Expand Down

0 comments on commit b31ee5b

Please sign in to comment.