diff --git a/PCL.Core/App/Configuration/Storage/FileConfigStorage.cs b/PCL.Core/App/Configuration/Storage/FileConfigStorage.cs index 07c166534..5ab55d1e9 100644 --- a/PCL.Core/App/Configuration/Storage/FileConfigStorage.cs +++ b/PCL.Core/App/Configuration/Storage/FileConfigStorage.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Runtime.CompilerServices; +using System.Text.Json; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; @@ -101,7 +103,34 @@ protected override bool OnAccess( { case StorageAction.Get: if (!File.Exists(strKey)) return false; - value = File.Get(strKey); + try + { + value = File.Get(strKey); + } + catch (Exception ex) when (ex is JsonException + or InvalidCastException + or FormatException + or OverflowException + or ArgumentException + or KeyNotFoundException + or InvalidDataException) + { + LogWrapper.Warn(ex, "Config", $"配置项 {strKey} 读取失败(可能已损坏),重置为默认值"); + if (!_writeActionChannel.Writer.TryWrite((strKey, () => File.Remove(strKey)))) + { + LogWrapper.Warn("Config", $"配置项 {strKey} 清理任务入队失败,改为同步删除"); + try + { + File.Remove(strKey); + File.Sync(); + } + catch (Exception cleanupEx) + { + LogWrapper.Error(cleanupEx, "Config", $"配置项 {strKey} 同步删除失败,可能需人工处理"); + } + } + return false; + } return true; case StorageAction.Exists: // 由于 Exists 的 value 类型一定是 bool,此处可 unsafe 直接赋值 diff --git a/PCL.Core/App/Configuration/Storage/JsonFileProvider.cs b/PCL.Core/App/Configuration/Storage/JsonFileProvider.cs index 590108d77..43881a411 100644 --- a/PCL.Core/App/Configuration/Storage/JsonFileProvider.cs +++ b/PCL.Core/App/Configuration/Storage/JsonFileProvider.cs @@ -79,7 +79,7 @@ public override T Get(string key) Set(key, fallback); return fallback; } - Exception GetNullException() => new NullReferenceException($"Deserialized value is null: '{key}'"); + Exception GetNullException() => new InvalidDataException($"Deserialized value is null: '{key}'"); } public override void Set(string key, T value)