Skip to content

Improve anonymous serialization exception message #5706

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 21, 2021
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Elasticsearch.Net.Utf8Json.Formatters;
Expand Down Expand Up @@ -1318,7 +1320,34 @@ public DynamicMethodAnonymousFormatter(byte[][] stringByteKeysField, object[] se
public void Serialize(ref JsonWriter writer, T value, IJsonFormatterResolver formatterResolver)
{
if (_serialize == null) throw new InvalidOperationException(GetType().Name + " does not support Serialize.");
_serialize(_stringByteKeysField, _serializeCustomFormatters, ref writer, value, formatterResolver);

try
{
_serialize(_stringByteKeysField, _serializeCustomFormatters, ref writer, value, formatterResolver);
}
catch (Exception e)
{
var type = value.GetType();
var properties = type.GetProperties();

var message = $"Failed to serialize anonymous type: {type}.";

if (properties.Any())
{
var sb = new StringBuilder()
.AppendLine(message).AppendLine("The type defines the following properties:");

foreach (var property in properties)
sb.AppendLine($"'{property.Name}' of type {property.PropertyType}");

message = sb.ToString().TrimEnd(Environment.NewLine.ToCharArray());
}

throw new AnonymousTypeSerializationException(message, e)
{
AnonymousType = type
};
}
}

public T Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
Expand All @@ -1327,4 +1356,15 @@ public T Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterReso
return _deserialize(_deserializeCustomFormatters, ref reader, formatterResolver);
}
}

public class AnonymousTypeSerializationException : SerializationException
{
public AnonymousTypeSerializationException() { }

public AnonymousTypeSerializationException(string message) : base(message) { }

public AnonymousTypeSerializationException(string message, Exception innerException) : base(message, innerException) { }

public Type AnonymousType { get; set; }
}
}