2012-02-29 5 views
7
MonoTouch에서

, 나는 캐치되지 않는 예외 핸들러 (또는 유사한 기능)의 Obj-C에서MonoTouch : uncaughtExceptionHandler?

등록 방법은 다음과 같습니다

void uncaughtExceptionHandler(NSException *exception) { 
     [FlurryAnalytics logError:@"Uncaught" message:@"Crash!" exception:exception]; 
    } 

- (void)applicationDidFinishLaunching:(UIApplication *)application { 
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler); 
    [FlurryAnalytics startSession:@" "]; 
    .... 
} 

답변

-4

당신은 NSExceptions을 던져 (수)하는 코드 주위에 시도 - 캐치 처리기를 추가를 :

try { 
    FlurryAnalytics.StartSession (" "); 
} catch (MonoTouchException ex) { 
    Console.WriteLine ("Could not start flurry analytics: {0}", ex.Message); 
} 

MonoTouch는 이미 캐치되지 않은 예외 처리기를 설치하고 이러한 ObjectiveC 예외를 관리 예외로 자동 변환합니다.

+2

이것은 실제로 원래 질문을 다루지 않습니다. –

1
public delegate void NSUncaughtExceptionHandler(IntPtr exception); 

    [DllImport("/System/Library/Frameworks/Foundation.framework/Foundation")] 
    private static extern void NSSetUncaughtExceptionHandler(IntPtr handler); 

    // This is the main entry point of the application. 
    private static void Main(string[] args) 
    { 
      NSSetUncaughtExceptionHandler(
       Marshal.GetFunctionPointerForDelegate(new NSUncaughtExceptionHandler(MyUncaughtExceptionHandler))); 

      ... 
    } 

    [MonoPInvokeCallback(typeof(NSUncaughtExceptionHandler))] 
    private static void MyUncaughtExceptionHandler(IntPtr exception) 
    { 
     var e = new NSException(exception); 
     ... 
    } 
+0

굉장합니다, 고마워요! 유일한 것은 IntPtr을 취하는 NSException의 생성자가 보호되어 있기 때문에 하위 형식을 지정하고 해당 버전의 생성자를 노출해야합니다. 그렇지 않으면 이것은 매우 도움이되었습니다. –

+0

[Here] (http://stackoverflow.com/questions/37525472/create-nsexception-from-intptr/37527174#37527174)'NSException'이 인수로'IntPtr'을 받아들이는 것을 볼 수 있습니다. – testing

0

이 작업을 수행합니다. 앱 실행시 SetupExceptionHandling() 메서드를 호출합니다. 마술은 NSRunLoop 부분입니다. 그러나 그 시점에서 예측할 수없는 영향으로 앱이 이상한 상태가 될 것입니다. 따라서 사용자가 예외를 처리하기로 결정한 후에 (예 : 다시 던지기) 앱을 종료하는 것이 좋습니다.

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); 
    } 
}