跳到主要内容

未处理的异常

Avalonia offer Dispatcher.UIThread.UnhandledException and Dispatcher.UIThread.UnhandledExceptionFilter. These APIs allow you to observe and optionally mark UI-thread exceptions as handled. However, this should be used with care: marking an exception as handled does not guarantee that the application can safely continue running. For this reason, it is still strongly recommended to catch and recover from exceptions locally when your application can reliably do so, and to use the global handlers primarily for logging, reporting, and last-resort mitigation.

Example:

Dispatcher.UIThread.UnhandledException += (s, e) =>
{
Console.WriteLine($"Unhandled: {e.Exception}");
// e.Handled = true; // Optional, use carefully
};

日志记录

我们建议将异常记录到控制台、文件或其他地方。有许多可用的日志记录库,例如 SerilogNLog

全局 try-catch

您可以在 Program.cs 文件中捕获主线程(也是 Avalonia UI 的 UI 线程)中的任何异常。为此,我们只需将整个 void Main 包装在 trycatch 块中。在 catch 块中,您可以记录错误、通知用户、发送日志文件或重新启动应用程序。

// File: Program.cs

public static void Main(string[] args)
{
try
{
// 在此处准备和运行您的 App
BuildAvaloniaApp()
.StartWithClassicDesktopLifetime(args);
}
catch (Exception e)
{
// 在这里我们可以处理异常,例如将其添加到日志文件中
Log.Fatal(e, "发生了一些非常糟糕的事情");
}
finally
{
// 此块是可选的。
// 如果需要清理或类似操作,请使用 finally 块
Log.CloseAndFlush();
}
}

来自其他线程的异常

如果您使用 Task 异步运行某些工作,可以设置 TaskScheduler.UnobservedTaskException。有关更多信息,请阅读 Microsoft .NET 文档

来自 Reactive UI 的异常

如果您将 Avalonia 与 ReactiveUI 一起使用,可以订阅它们的 RxApp.DefaultExceptionHandler。有关更多信息,请参阅 ReactiveUI 默认异常处理程序

注意,RxApp.DefaultExceptionHandler 应在创建任何 ReactiveCommand 之前设置。否则,自定义处理程序将不会被使用。您可以在应用程序入口点或在创建任何 Avalonia 视图或窗口之前设置它。"