diff --git a/JiLinApp/Core/Avalonia/RxAppExceptionHandler.cs b/JiLinApp/Core/Avalonia/RxAppExceptionHandler.cs new file mode 100644 index 0000000..37bbac2 --- /dev/null +++ b/JiLinApp/Core/Avalonia/RxAppExceptionHandler.cs @@ -0,0 +1,42 @@ +using System; +using System.Diagnostics; + +namespace JiLinApp.Core.Avalonia; + +public class RxAppExceptionHandler : IObserver +{ + private static RxAppExceptionHandler? _instance; + + public static RxAppExceptionHandler Instance + { + get + { + return _instance ??= new(); + } + } + + public delegate void ExceptionHandler(Exception e); + + public event ExceptionHandler? OnExceptionHandler; + + public void OnNext(Exception e) + { + if (Debugger.IsAttached) Debugger.Break(); + OnException(e); + } + + public void OnError(Exception e) + { + if (Debugger.IsAttached) Debugger.Break(); + OnException(e); + } + + public void OnCompleted() + { + } + + private void OnException(Exception e) + { + OnExceptionHandler?.Invoke(e); + } +} \ No newline at end of file diff --git a/JiLinApp/JiLinApp.csproj b/JiLinApp/JiLinApp.csproj index 32b1aad..b924979 100644 --- a/JiLinApp/JiLinApp.csproj +++ b/JiLinApp/JiLinApp.csproj @@ -6,6 +6,7 @@ true app.manifest true + zh-Hans diff --git a/JiLinApp/Program.cs b/JiLinApp/Program.cs index 3a8ee81..b4744d0 100644 --- a/JiLinApp/Program.cs +++ b/JiLinApp/Program.cs @@ -1,7 +1,10 @@ using Avalonia; using Avalonia.Media; using Avalonia.ReactiveUI; +using JiLinApp.Core.Avalonia; +using ReactiveUI; using System; +using System.Threading.Tasks; namespace JiLinApp; @@ -11,12 +14,25 @@ internal class Program // SynchronizationContext-reliant code before AppMain is called: things aren't initialized // yet and stuff might break. [STAThread] - public static void Main(string[] args) => BuildAvaloniaApp() - .StartWithClassicDesktopLifetime(args); + public static void Main(string[] args) + { + GlobalInit(); + try + { + AppBuilder appBuilder = BuildAvaloniaApp(); + appBuilder.StartWithClassicDesktopLifetime(args); + } + catch (Exception) + { + //The global try-catch + throw; + } + } // Avalonia configuration, don't remove; also used by visual designer. public static AppBuilder BuildAvaloniaApp() - => AppBuilder.Configure() + { + return AppBuilder.Configure() .UsePlatformDetect() .WithInterFont() .LogToTrace() @@ -32,4 +48,24 @@ internal class Program } } }); + } + + #region extend + + private static void GlobalInit() + { + // HandleExceptions + // Exceptions from another thread + TaskScheduler.UnobservedTaskException += (sender, e) => + { + e.SetObserved(); + }; + // Exceptions from Reactive UI + RxAppExceptionHandler.Instance.OnExceptionHandler += e => + { + }; + RxApp.DefaultExceptionHandler = RxAppExceptionHandler.Instance; + } + + #endregion extend } \ No newline at end of file