Xamarin Forms 在文件中保存异常

Xamarin Forms save exceptions in a file

我希望能够查看我的应用程序崩溃时抛出的异常并将其保存在文件中。有关于这个主题的教程吗?我看过 Advanced App Lifecycle Demos 和那里的崩溃处理,但我真的不明白如何在我的应用程序中实现它。

你最好使用 Xamarin Insights,一个应用程序日志框架,它会自动为你记录崩溃和未处理的异常。

单独获取导致整个崩溃的异常并不容易。幸运的是,有一种方法可以使用 Xamarin Insights 获取异常。它可供 Xamarin 客户免费使用。

您只需在网站上为您的应用获取一个 API 密钥,添加 NuGet 包 Xamarin.Isights 并按照应用中 here 的描述对其进行初始化。 然后,每次用户在崩溃后启动您的应用程序时,您都会收到崩溃报告。

如果您遇到启动崩溃,那么您可以使用这些代码行来初始化 Xamarin.Insights 以接收有关它们的报告:

Insights.HasPendingCrashReport += (sender, isStartupCrash) =>
{
  if (isStartupCrash) {
    Insights.PurgePendingCrashReports().Wait();
  }
};
Insights.Initialize("Your API Key");

在我们的团队中,我们不喜欢 Xamarin Insights,所以我们使用这样的结构:

    public async Task SafeCall(Func<Task> action)
    {
        var workedWrong = false;
        try
        {
            await action();
        }
        catch (Exception e)
        {
            workedWrong = true;
            // Here you copy all the data you need.
        }

        if (workedWrong)
        {
            // Here you show the notification that something went wrong and write all the relevant information to the file (you can find how to do it in official Xamarin manual).
        }
    }

尽管它没有捕捉到 iOS 异常。