MonoTouch: uncaughtExceptionHandler?

前端 未结 3 454
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 10:19

In MonoTouch, how do I register an uncaught exception handler (or similar function)

In Obj-C:

void uncaughtExceptionHandler(NSException *exception) {         


        
3条回答
  •  臣服心动
    2021-01-12 10:43

    This does the job. Call the SetupExceptionHandling() method on app launch. The magic is the NSRunLoop part. But the app is going to be in a weird state at that point, with unpredictable effects. Therefore, I would strongly suggest killing the app after the user decides what to do with the exception -- for example, by re-throwing it.

    public static class IOSStartupTasks {
      private static bool _HaveHandledException;
      public static void HandleException(object sender, UnhandledExceptionEventArgs e) {
        if (!(_HaveHandledException)) {
          _HaveHandledException = true;
          UIAlertView alert = new UIAlertView("Error", "Bad news", "report", "just crash");
          alert.Delegate = whatever; // delegate object should take the exception as an argument and rethrow when it's done handling user input.
          alert.Show();
          NSRunLoop.Current.RunUntil(NSDate.DistantFuture); // keeps the app alive, but likely with weird effects, so make sure you don't let the user back into the main app.
        }
      }
    
      public static void SetupExceptionHandling() {
        AppDomain domain = AppDomain.CurrentDomain;
        domain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => 
          IOSStartupTasks.HandleException(sender, e);
      }
    }
    

提交回复
热议问题