【问题标题】:Xamarin Forms, how to log unhandled exceptionXamarin Forms,如何记录未处理的异常
【发布时间】:2018-10-22 12:55:25
【问题描述】:

我的 Xamarin Forms 项目中有以下代码。我使用 SentryErrorLog 记录异常并将异常消息保存到本地 pp 设备。我已经测试了以下代码并且记录成功。但是我发现当有未知异常导致App崩溃时,Sentry和ExternalStorageDirectory都没有日志。未知异常导致应用关闭并弹出消息“{App name}已停止”。

因为没有异常的日志,所以不知道怎么排查。而且这种异常只是偶尔发生,我很难找到原因。所以我想知道我是否错过了任何捕获异常的代码?或者有时Android会在App触发异常事件处理程序之前关闭App?

    public override void OnCreate()
    {
        base.OnCreate();

        ravenClient = SentryErrorLog.CreateRavenClient();
        AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
    }

    private void AndroidEnvironment_UnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
    {
        ravenClient.LogException(e.Exception);
        LogExceptionLocally(e.Exception);
    }

    private void LogExceptionLocally(Exception e)
    {
        // Log to ExternalStorageDirectory
    }

或者我应该使用其他崩溃记录器?

【问题讨论】:

    标签: xamarin.forms error-logging


    【解决方案1】:

    您可以在下面添加这些代码来记录未处理的异常:

    安卓:

    // In OnCreate,
    
    AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
    TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
    AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironmentOnUnhandledException;
    

    iOS:

    // In FinishedLaunching:
    
    AppDomain.CurrentDomain.UnhandledException += async (sender, e) =>
    TaskScheduler.UnobservedTaskException += async (sender, e) =>
    

    UWP:

    // In OnLaunched:
    
    UnhandledException += OnUnhandledException;
    

    以下是一些可能有帮助的链接:

    Logging Xamarin unhandled (Android uncaught) exceptions

    https://forums.xamarin.com/discussion/103962/go-back-to-mainpage-if-there-is-an-unhandled-exception

    【讨论】:

    • 我试过AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;。我手动抛出一个异常进行测试,我发现UnhandledExceptionUnhandledExceptionRaiser 都被触发了,所以我得到了一个异常的2个日志。预计不会出现重复的日志。这两个事件有什么区别?我只是担心操作系统可能会在应用程序开始记录异常之前关闭应用程序。
    • 别担心。如果您的应用因应用中的异常而崩溃,您的应用可以在关闭之前记录异常。
    • 其实这两个事件并没有太大区别,可以参考forums.xamarin.com/discussion/3071/…查看区别。
    • 感谢您的帮助,在我添加了AppDomain.CurrentDomain.UnhandledException 之后,我发现了异常,即 AndroidRuntime 错误。但是UnhandledExceptionRaiser 没有抓住它。那么看起来UnhandledException 处理程序可以捕获更广泛的异常?根据您上面的链接,看起来UnhandledExceptionRaiser 将.NET 异常转换为适当的Java 端异常,这在某些情况下可能是必要的?我只能使用UnhandledException 吗?如果我同时添加两者,我会得到重复的日志。
    • 您只能使用UnhandledException。并参考developer.xamarin.com/api/event/… 了解UnhandledExceptionRaiser 的作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多