Skip to content
This repository was archived by the owner on Jun 1, 2024. It is now read-only.

Commit f8bfaf8

Browse files
piastemivano
authored andcommitted
[Urgent] Fix KeyNotFoundException when items[i].errors is undefined (#271)
* Fix KeyNotFoundException * removed gitignore entry * fix gitignore newline
1 parent 9d9930e commit f8bfaf8

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

src/Serilog.Sinks.Elasticsearch/Sinks/ElasticSearch/ElasticSearchSink.cs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ protected override void EmitBatch(IEnumerable<LogEvent> events)
7272
var items = result.Body["items"];
7373
foreach (var item in items)
7474
{
75-
if (item["index"] != null && item["index"]["error"] != null)
75+
if (item["index"] != null && HasProperty(item["index"], "error") && item["index"]["error"] != null)
7676
{
7777
var e = events.ElementAt(indexer);
7878
if (_state.Options.EmitEventFailure.HasFlag(EmitEventFailureHandling.WriteToSelfLog))
@@ -219,5 +219,17 @@ protected virtual void HandleException(Exception ex, IEnumerable<LogEvent> event
219219
if (_state.Options.EmitEventFailure.HasFlag(EmitEventFailureHandling.ThrowException))
220220
throw ex;
221221
}
222+
223+
// Helper function: checks if a given dynamic member / dictionary key exists at runtime
224+
private static bool HasProperty(dynamic settings, string name)
225+
{
226+
if (settings is System.Dynamic.ExpandoObject)
227+
return ((IDictionary<string, object>)settings).ContainsKey(name);
228+
229+
if (settings is System.Dynamic.DynamicObject)
230+
return ((System.Dynamic.DynamicObject)settings).GetDynamicMemberNames().Contains(name);
231+
232+
return settings.GetType().GetProperty(name) != null;
233+
}
222234
}
223235
}

0 commit comments

Comments
 (0)