Handle xml errors in Persistent.Load gracefully

This commit is contained in:
Brant Martin
2019-06-05 13:56:08 -04:00
parent 121846eeae
commit d97a6a52a4

View File

@@ -7,6 +7,7 @@ using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml.Serialization; using System.Xml.Serialization;
using NLog;
namespace Torch namespace Torch
{ {
@@ -17,6 +18,7 @@ namespace Torch
/// <typeparam name="T">Data class type</typeparam> /// <typeparam name="T">Data class type</typeparam>
public sealed class Persistent<T> : IDisposable where T : new() public sealed class Persistent<T> : IDisposable where T : new()
{ {
private static Logger _log = LogManager.GetCurrentClassLogger();
public string Path { get; set; } public string Path { get; set; }
private T _data; private T _data;
public T Data public T Data
@@ -78,10 +80,18 @@ namespace Torch
if (File.Exists(path)) if (File.Exists(path))
{ {
var ser = new XmlSerializer(typeof(T)); try
using (var f = File.OpenText(path))
{ {
config = new Persistent<T>(path, (T)ser.Deserialize(f)); var ser = new XmlSerializer(typeof(T));
using (var f = File.OpenText(path))
{
config = new Persistent<T>(path, (T)ser.Deserialize(f));
}
}
catch (Exception ex)
{
_log.Error(ex);
config = null;
} }
} }
if (config == null) if (config == null)