Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions YamlDotNet.Test/Analyzers/StaticGenerator/HandleExceptionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.IO;
using FluentAssertions;
using Xunit;
using YamlDotNet.Serialization;

namespace YamlDotNet.Test.Analyzers.StaticGenerator
{
public class HandleExceptionTests
{
[Fact]
public void StaticSerializationHandlesTargetInvocationException()
{
var obj = new ThrowingPropertyExample();
var serializer = new StaticSerializerBuilder(new StaticContext())
.WithExceptionHandler((e, o, p) =>
$"Exception of type {e.GetType().FullName} was thrown in property {p} " +
"of " + (ReferenceEquals(o, obj) ? "expected" : "unexpected") + " object")
.Build();
var writer = new StringWriter();

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

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

[Fact]
public void StaticSerializationDoesntHandleTargetInvocationExceptionByDefault()
{
var serializer = new StaticSerializerBuilder(new StaticContext()).Build();
var writer = new StringWriter();
var obj = new ThrowingPropertyExample();

Assert.Throws<InvalidOperationException>(() => serializer.Serialize(writer, obj));
}
}

[YamlSerializable]
public class ThrowingPropertyExample
{
public string Value => throw new InvalidOperationException();
}
}
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
29 changes: 29 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
using YamlDotNet.Serialization.Callbacks;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Test.Analyzers.StaticGenerator;

namespace YamlDotNet.Test.Serialization
{
Expand Down Expand Up @@ -1117,6 +1118,34 @@ public void SerializationEmitsPropertyWhenValueDifferFromDefaultValueAttribute()
serialized.Should().Contain("Value");
}

[Fact]
public void SerializationHandlesException()
{
var obj = new ThrowingPropertyExample();
var serializer = new SerializerBuilder()
.WithExceptionHandler((e, o, p) =>
$"Exception of type {e.GetType().FullName} was thrown in property {p} " +
"of " + (ReferenceEquals(o, obj) ? "expected" : "unexpected") + " object")
.Build();
var writer = new StringWriter();

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

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

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

Assert.Throws<TargetInvocationException>(() => Serializer.Serialize(writer, obj));
}

[Fact]
public void SerializingAGenericDictionaryShouldNotThrowTargetException()
{
Expand Down
20 changes: 19 additions & 1 deletion YamlDotNet/Serialization/PropertyDescriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ public bool CanWrite
get { return baseDescriptor.CanWrite; }
}

public Func<Exception, object, string, string>? ExceptionHandler { get; set; }

public void Write(object target, object? value)
{
baseDescriptor.Write(target, value);
Expand All @@ -69,7 +71,23 @@ public void Write(object target, object? value)

public IObjectDescriptor Read(object target)
{
return baseDescriptor.Read(target);
if (ExceptionHandler == null)
{
return baseDescriptor.Read(target);
}

try
{
return baseDescriptor.Read(target);
}
catch (Exception e)
{
return new ObjectDescriptor(
ExceptionHandler(e, target, Name),
typeof(string),
typeof(string),
ScalarStyle.Any);
}
}
}
}
18 changes: 17 additions & 1 deletion YamlDotNet/Serialization/SerializerBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

using System;
using System.Collections.Generic;
using System.Reflection;
#if NET7_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
Expand Down Expand Up @@ -62,6 +63,7 @@ public sealed class SerializerBuilder : BuilderSkeleton<SerializerBuilder>
private ScalarStyle defaultScalarStyle = ScalarStyle.Any;
private bool quoteNecessaryStrings;
private bool quoteYaml1_1Strings;
private Func<Exception, object, string, string>? exceptionHandler;

public SerializerBuilder()
: base(new DynamicTypeResolver())
Expand Down Expand Up @@ -129,6 +131,19 @@ public SerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings =
return this;
}

/// <summary>
/// Enables handling an exception thrown by a property so that information about exception is serialized as string value of the property.
/// </summary>
/// <param name="exceptionHandler">
/// A function that takes the caught exception, the object and the name of the object's property (from which the exception was thrown).
/// The string returned from the function is written instead of the property value by the serializer.
/// </param>
public SerializerBuilder WithExceptionHandler(Func<Exception, object, string, string> exceptionHandler)
{
this.exceptionHandler = exceptionHandler;
return this;
}

/// <summary>
/// Sets the default quoting style for scalar values. The default value is <see cref="ScalarStyle.Any"/>
/// </summary>
Expand Down Expand Up @@ -695,7 +710,8 @@ public IValueSerializer BuildValueSerializer()

internal ITypeInspector BuildTypeInspector()
{
ITypeInspector innerInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties);
ITypeInspector innerInspector = new ReadablePropertiesTypeInspector(
typeResolver, includeNonPublicProperties, exceptionHandler);

if (!ignoreFields)
{
Expand Down
16 changes: 16 additions & 0 deletions YamlDotNet/Serialization/StaticSerializerBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

using System;
using System.Collections.Generic;
using System.Reflection;
#if NET7_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
Expand Down Expand Up @@ -126,6 +127,21 @@ public StaticSerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Stri
return this;
}

/// <summary>
/// Enables handling an exception thrown by a property so that information about exception is serialized as string value of the property.
/// </summary>
/// <param name="exceptionHandler">
/// A function that takes the caught exception, the object and the name of the object's property (from which the exception was thrown).
/// The string returned from the function is written instead of the property value by the serializer.
/// </param>
public StaticSerializerBuilder WithExceptionHandler(Func<Exception, object, string, string> exceptionHandler)
{
typeInspectorFactories.Add(
typeof(ExceptionHandlerInspector),
inner => new ExceptionHandlerInspector(inner, exceptionHandler));
return this;
}

/// <summary>
/// Put double quotes around strings that need it, for example Null, True, False, a number. This should be called before any other "With" methods if you want this feature enabled.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace YamlDotNet.Serialization.TypeInspectors
{
/// <summary>
/// Sets HandleTargetInvocationExceptions to true for all property descriptors.
/// </summary>
public sealed class ExceptionHandlerInspector : TypeInspectorSkeleton
{
private readonly ITypeInspector innerTypeDescriptor;
private readonly Func<Exception, object, string, string> exceptionHandler;

public ExceptionHandlerInspector(
ITypeInspector innerTypeDescriptor, Func<Exception, object, string, string> exceptionHandler)
{
this.innerTypeDescriptor = innerTypeDescriptor;
this.exceptionHandler = exceptionHandler;
}

public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container)
{
return innerTypeDescriptor.GetProperties(type, container)
.Select(p =>
{
var descriptor = new PropertyDescriptor(p) { ExceptionHandler = exceptionHandler };
return (IPropertyDescriptor)descriptor;
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,21 @@ public sealed class ReadablePropertiesTypeInspector : TypeInspectorSkeleton
{
private readonly ITypeResolver typeResolver;
private readonly bool includeNonPublicProperties;
private readonly Func<Exception, object, string, string>? exceptionHandler;

public ReadablePropertiesTypeInspector(ITypeResolver typeResolver)
: this(typeResolver, false)
{
}

public ReadablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties)
public ReadablePropertiesTypeInspector(
ITypeResolver typeResolver,
bool includeNonPublicProperties,
Func<Exception, object, string, string>? exceptionHandler = null)
{
this.typeResolver = typeResolver ?? throw new ArgumentNullException(nameof(typeResolver));
this.includeNonPublicProperties = includeNonPublicProperties;
this.exceptionHandler = exceptionHandler;
}

private static bool IsValidProperty(PropertyInfo property)
Expand All @@ -57,18 +62,23 @@ public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object
return type
.GetProperties(includeNonPublicProperties)
.Where(IsValidProperty)
.Select(p => (IPropertyDescriptor)new ReflectionPropertyDescriptor(p, typeResolver));
.Select(p => (IPropertyDescriptor)new ReflectionPropertyDescriptor(p, typeResolver, exceptionHandler));
}

private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor
{
private readonly PropertyInfo propertyInfo;
private readonly ITypeResolver typeResolver;
private readonly Func<Exception, object, string, string>? exceptionHandler;

public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver)
public ReflectionPropertyDescriptor(
PropertyInfo propertyInfo,
ITypeResolver typeResolver,
Func<Exception, object, string, string>? exceptionHandler)
{
this.propertyInfo = propertyInfo ?? throw new ArgumentNullException(nameof(propertyInfo));
this.typeResolver = typeResolver ?? throw new ArgumentNullException(nameof(typeResolver));
this.exceptionHandler = exceptionHandler;
ScalarStyle = ScalarStyle.Any;
}

Expand All @@ -92,7 +102,27 @@ public void Write(object target, object? value)

public IObjectDescriptor Read(object target)
{
var propertyValue = propertyInfo.ReadValue(target);
object? propertyValue;
if (exceptionHandler != null)
{
try
{
propertyValue = propertyInfo.ReadValue(target);
}
catch (TargetInvocationException e)
{
return new ObjectDescriptor(
exceptionHandler(e.InnerException!, target, propertyInfo.Name),
typeof(string),
typeof(string),
ScalarStyle.Any);
}
}
else
{
propertyValue = propertyInfo.ReadValue(target);
}

var actualType = TypeOverride ?? typeResolver.Resolve(Type, propertyValue);
return new ObjectDescriptor(propertyValue, actualType, Type, ScalarStyle);
}
Expand Down