11using System ;
22using System . Collections . Generic ;
3+ using Elasticsearch . Net ;
34using Newtonsoft . Json ;
5+ using Newtonsoft . Json . Linq ;
46
57namespace Nest
68{
@@ -15,22 +17,55 @@ public abstract class DictionaryResponseBase<TKey, TValue> : ResponseBase, IDict
1517 IReadOnlyDictionary < TKey , TValue > IDictionaryResponse < TKey , TValue > . BackingDictionary { get ; set ; }
1618 }
1719
20+ internal class DictionaryResponseJsonConverterHelpers
21+ {
22+ public static JObject ReadServerErrorFirst ( JsonReader reader , out Error error , out int ? statusCode )
23+ {
24+ var j = JObject . Load ( reader ) ;
25+ var errorProperty = j . Property ( "error" ) ;
26+ error = null ;
27+ if ( errorProperty ? . Value ? . Type == JTokenType . String )
28+ {
29+ var reason = errorProperty . Value . Value < string > ( ) ;
30+ error = new Error { Reason = reason } ;
31+ errorProperty . Remove ( ) ;
32+ }
33+ else if ( errorProperty ? . Value ? . Type == JTokenType . Object && ( ( JObject ) errorProperty . Value ) [ "reason" ] != null )
34+ {
35+ error = errorProperty . Value . ToObject < Error > ( ) ;
36+ errorProperty . Remove ( ) ;
37+ }
38+ var statusProperty = j . Property ( "status" ) ;
39+ statusCode = null ;
40+ if ( statusProperty ? . Value ? . Type == JTokenType . Integer )
41+ {
42+ statusCode = statusProperty . Value . Value < int > ( ) ;
43+ statusProperty . Remove ( ) ;
44+ }
45+ return j ;
46+ }
47+ }
48+
1849 internal class DictionaryResponseJsonConverter < TResponse , TKey , TValue > : JsonConverter
19- where TResponse : IDictionaryResponse < TKey , TValue > , new ( )
50+ where TResponse : ResponseBase , IDictionaryResponse < TKey , TValue > , new ( )
2051 {
2152 public override bool CanConvert ( Type objectType ) => true ;
2253 public override bool CanRead => true ;
2354 public override bool CanWrite => false ;
2455
2556 public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer )
2657 {
58+ var j = DictionaryResponseJsonConverterHelpers . ReadServerErrorFirst ( reader , out var error , out var statusCode ) ;
2759 var response = new TResponse ( ) ;
2860 var dict = new Dictionary < TKey , TValue > ( ) ;
29- serializer . Populate ( reader , dict ) ;
61+ serializer . Populate ( j . CreateReader ( ) , dict ) ;
3062 response . BackingDictionary = dict ;
63+ response . Error = error ;
64+ response . StatusCode = statusCode ;
3165 return response ;
3266 }
3367
3468 public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer ) { }
69+
3570 }
3671}
0 commit comments