Skip to content

Commit 9fe1b57

Browse files
Improve anonymous serialization exception (#5706) (#5707)
Co-authored-by: Steve Gordon <sgordon@hotmail.co.uk>
1 parent ad1f09a commit 9fe1b57

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

src/Elasticsearch.Net/Utf8Json/Resolvers/DynamicObjectResolver.cs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
using System.Linq;
3232
using System.Reflection;
3333
using System.Reflection.Emit;
34+
using System.Runtime.Serialization;
35+
using System.Text;
3436
using System.Text.RegularExpressions;
3537
using System.Threading;
3638
using Elasticsearch.Net.Utf8Json.Formatters;
@@ -1318,7 +1320,34 @@ public DynamicMethodAnonymousFormatter(byte[][] stringByteKeysField, object[] se
13181320
public void Serialize(ref JsonWriter writer, T value, IJsonFormatterResolver formatterResolver)
13191321
{
13201322
if (_serialize == null) throw new InvalidOperationException(GetType().Name + " does not support Serialize.");
1321-
_serialize(_stringByteKeysField, _serializeCustomFormatters, ref writer, value, formatterResolver);
1323+
1324+
try
1325+
{
1326+
_serialize(_stringByteKeysField, _serializeCustomFormatters, ref writer, value, formatterResolver);
1327+
}
1328+
catch (Exception e)
1329+
{
1330+
var type = value.GetType();
1331+
var properties = type.GetProperties();
1332+
1333+
var message = $"Failed to serialize anonymous type: {type}.";
1334+
1335+
if (properties.Any())
1336+
{
1337+
var sb = new StringBuilder()
1338+
.AppendLine(message).AppendLine("The type defines the following properties:");
1339+
1340+
foreach (var property in properties)
1341+
sb.AppendLine($"'{property.Name}' of type {property.PropertyType}");
1342+
1343+
message = sb.ToString().TrimEnd(Environment.NewLine.ToCharArray());
1344+
}
1345+
1346+
throw new AnonymousTypeSerializationException(message, e)
1347+
{
1348+
AnonymousType = type
1349+
};
1350+
}
13221351
}
13231352

13241353
public T Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
@@ -1327,4 +1356,15 @@ public T Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterReso
13271356
return _deserialize(_deserializeCustomFormatters, ref reader, formatterResolver);
13281357
}
13291358
}
1359+
1360+
public class AnonymousTypeSerializationException : SerializationException
1361+
{
1362+
public AnonymousTypeSerializationException() { }
1363+
1364+
public AnonymousTypeSerializationException(string message) : base(message) { }
1365+
1366+
public AnonymousTypeSerializationException(string message, Exception innerException) : base(message, innerException) { }
1367+
1368+
public Type AnonymousType { get; set; }
1369+
}
13301370
}

0 commit comments

Comments
 (0)