31
31
using System . Linq ;
32
32
using System . Reflection ;
33
33
using System . Reflection . Emit ;
34
+ using System . Runtime . Serialization ;
35
+ using System . Text ;
34
36
using System . Text . RegularExpressions ;
35
37
using System . Threading ;
36
38
using Elasticsearch . Net . Utf8Json . Formatters ;
@@ -1318,7 +1320,34 @@ public DynamicMethodAnonymousFormatter(byte[][] stringByteKeysField, object[] se
1318
1320
public void Serialize ( ref JsonWriter writer , T value , IJsonFormatterResolver formatterResolver )
1319
1321
{
1320
1322
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
+ }
1322
1351
}
1323
1352
1324
1353
public T Deserialize ( ref JsonReader reader , IJsonFormatterResolver formatterResolver )
@@ -1327,4 +1356,15 @@ public T Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterReso
1327
1356
return _deserialize ( _deserializeCustomFormatters , ref reader , formatterResolver ) ;
1328
1357
}
1329
1358
}
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
+ }
1330
1370
}
0 commit comments