如何为 MAUI 应用程序创建全局错误处理

Ste*_*hka 16 maui

有没有办法为 MAUI 应用程序设置全局错误处理程序?当我从 Visual Studio 启动我的应用程序时,它当前运行良好。但是,在所有模拟器上,如果我尝试从 shell 的应用程序图标启动应用程序,它会启动然后退出(在 iOS 上,我会收到故障转储)。我不知道这发生在哪里,所以想尝试捕获全局处理程序。

我查看了 builder.ConfigureMauiHandlers,但它似乎只适用于控件。您不能使用 UnhandledExceptionEventHandler 类型,这是我认为合适的类型。

我还尝试了 AppDomain 处理程序,但它似乎也不起作用:

AppDomain ad = AppDomain.CurrentDomain;
ad.UnhandledException += Ad_UnhandledException;
Run Code Online (Sandbox Code Playgroud)

这可能吗?我只找到了 WCF 的示例,但它们不起作用。

dpe*_*ish 5

这里有一个相当长的 github 讨论:https://github.com/dotnet/maui/discussions/653 ?sort=top#discussioncomment-3434251

最受欢迎的回应来自一位 Sentry 开发人员,他提供了一种使用第一次机会异常的解决方案,如以下要点所示: https ://gist.github.com/mattjohnsonpint/7b385b7a2da7059c4a16562bc5ddb3b7

Windows 特定的实现包括以下处理程序,其中 _lastFirstChanceException 是私有静态变量。

    AppDomain.CurrentDomain.UnhandledException += (sender, args) => 
    {
        UnhandledException?.Invoke(sender, args);
    };
Run Code Online (Sandbox Code Playgroud)

...

    AppDomain.CurrentDomain.FirstChanceException += (_, args) =>
    {
        _lastFirstChanceException = args.Exception;
    };

    Microsoft.UI.Xaml.Application.Current.UnhandledException += (sender, args) =>
    {
        var exception = args.Exception;

        if (exception.StackTrace is null)
        {
            exception = _lastFirstChanceException;
        }

        UnhandledException?.Invoke(sender, new UnhandledExceptionEventArgs(exception, true));
    };
Run Code Online (Sandbox Code Playgroud)

虽然这适用于我的用例,但 SonarLint 确实表明静态构造函数方法存在一些问题。一种解决方案是使用带有 Lazy<MauiException> 的密封 MauiException 类来将其作为线程安全单例进行访问,正如 Jon Skeet 在此描述的那样:https: //csharpindepth.com/Articles/Singleton


Jim*_*mmy 2

我自己也为此苦苦挣扎了一段时间,最终使用了 Sentry.io,到目前为止给人留下了深刻的印象!