SettingsManager: ignore missing types & add error event

This commit is contained in:
2024-05-06 07:10:32 +02:00
parent 125e878103
commit c297286782

View File

@@ -2,6 +2,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
namespace Pilz.Configuration namespace Pilz.Configuration
{ {
@@ -10,6 +12,7 @@ namespace Pilz.Configuration
public event EventHandler AutoSavingSettings; public event EventHandler AutoSavingSettings;
public event EventHandler SavingSettings; public event EventHandler SavingSettings;
public event EventHandler SavedSettings; public event EventHandler SavedSettings;
public event EventHandler<ErrorEventArgs> OnSerializationError;
protected ISettings defaultInstance = null; protected ISettings defaultInstance = null;
protected bool enableAutoSave = false; protected bool enableAutoSave = false;
@@ -119,8 +122,21 @@ namespace Pilz.Configuration
return new JsonSerializerSettings() return new JsonSerializerSettings()
{ {
Formatting = Formatting.Indented, Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Auto TypeNameHandling = TypeNameHandling.Auto,
Error = JsonSerializer_OnError,
}; };
} }
protected virtual void JsonSerializer_OnError(object sender, ErrorEventArgs e)
{
const string errorResolvingType = "Error resolving type specified in JSON";
// Invoke event
OnSerializationError?.Invoke(sender, e);
// Handle ourself
if (!e.ErrorContext.Handled && e.ErrorContext.Error is JsonSerializationException serializationException && serializationException.Message.StartsWith(errorResolvingType))
e.ErrorContext.Handled = true;
}
} }
} }