处理全局异常机器人 | iOS

Handling Global Exception Xamarin | Droid | iOS

我们都知道移动平台是一个紧凑的平台,我们在构建应用程序时必须考虑很多东西。它可以是任何东西,例如Memory Performance Resolutions Architecture Implementation 等等。我们永远不知道什么时候以及什么原因导致应用程序在玩应用程序时崩溃成为一个大问题,它随时可能发生

e.g. App Launch, Load Screen, API Call, Binding Data, Loading Images etc.

请相信我,有时真的很难找到导致应用程序出现问题的位置和原因。我在论坛、技术社区和群组上看到很多 post 与同一问题相关,人们通常会问这样的问题:

  1. 应用程序在启动时崩溃。
  2. 应用程序在启动画面加载时崩溃。
  3. 显示图像时应用程序崩溃。
  4. 绑定来自 api 的数据时应用程序崩溃。

如何识别问题及其原因?

目的:我们在这里的目的是获取异常的堆栈跟踪数据,帮助我们确定问题的确切原因,无论是 Release Mode 还是 Debug Mode .我们将能够了解问题及其原因。我们会将此数据存储在一个 text 文件中,该文件将存储在设备存储中。


解决方案: 或者,您可以制作自己的洞察力采集器,如果在测试应用程序时出现问题,它将为您提供应用程序洞察力和线索。这将是你的,你可以随心所欲地调整。让我们深入了解全球 try{}catch{}

创建一个 Helper Class 文件,该文件具有为异常数据生成文本文件的方法。

public static class ExceptionFileWriter
{
    #region Property File Path

    static string FilePath
    {
        get
        {
            string path = string.Empty;
            var _fileName = "Fatal.txt";
#if __IOS__
            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Documents folder C:\ddddd
            string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder C:\dddd\...\library
            path = Path.Combine(libraryPath, _fileName); //c:\ddddd\...\library\NBCCSeva.db3
#else
#if __ANDROID__
            string dir = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "Exception");
        if (Directory.Exists(dir))
            return Path.Combine(dir, _fileName);
        path= Path.Combine(Directory.CreateDirectory(dir).FullName, _fileName);
#endif
#endif
            return path;
        }
    }

    #endregion

    #region ToLog Exception

    public static void ToLogUnhandledException(this Exception exception)
    {
        try
        {
            var errorMessage = String.Format("Time: {0}\r\nError: Unhandled Exception\r\n{1}\n\n", DateTime.Now, string.IsNullOrEmpty(exception.StackTrace) ? exception.ToString() : exception.StackTrace);
            File.WriteAllText(FilePath, errorMessage);
        }
        catch (Exception ex)
        {
            // just suppress any error logging exceptions
        }
    }

    #endregion
}

实施代码的时间:在您应用的 Application 文件或 Splash Activity 中订阅以下事件。我在这种情况下使用应用程序。

AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;

[Application]
public class ExceptionHandlingApp : Application
{
    #region Constructor

    public ExceptionHandlingApp(IntPtr javaReference, JniHandleOwnership transfer)
        : base(javaReference, transfer)
    {

    }

    #endregion

    #region OnCreate

    public override void OnCreate()
    {
        base.OnCreate();
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
        TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
    }

    #endregion

    #region Task Schedular Exception

    private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
    {
        var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);
        newExc.ToLogUnhandledException();
    }

    #endregion

    #region Current Domain Exception

    private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
    {
        var newExc = new Exception("CurrentDomainOnUnhandledException", unhandledExceptionEventArgs.ExceptionObject as Exception);
        newExc.ToLogUnhandledException();
    }

    #endregion
}

Note: You can find exceptions record file in Device Storage | File Manager > Exception Folder > fatal.txt

干杯!!

除了自己做之外,您还可以使用 Xamarin.Insights,因为 Xamarin 用户可以免费使用它,并且已经实现了所有平台。 您可以在线接收使用报告、崩溃报告等,而无需用户手动向您发送日志文件。

要接收崩溃报告,您唯一需要做的就是在您的应用程序启动时初始化 Xamarin.Insights:

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