簡體   English   中英

如何在Xamarin.Android中正確編寫自定義UncaughtExceptionHandler

[英]How to properly write a custom UncaughtExceptionHandler in Xamarin.Android

我想要實現的只是捕獲我的應用程序上的異常,以便我可以將它們發送到服務器。 我想通了,我可以寫我的自定義UncaughtExceptionHandler的基礎上,原生Android代碼Java中回答這樣做這里在StackOverflow上。

這是我的CustomExceptionHandler類:

public class CustomExceptionHandler : Thread.IUncaughtExceptionHandler
{
    public IntPtr Handle { get; private set; }

    public CustomExceptionHandler(Thread.IUncaughtExceptionHandler exceptionHandler)
    {
        Handle = exceptionHandler.Handle;
    }

    public void UncaughtException(Thread t, Throwable e)
    {
        // Submit exception details to a server
        ...

        // Display error message for local debugging purposes
        Debug.WriteLine(e);
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

然后我使用這個類在我的Activity中設置DefaultUncaughtExceptionHandler

// Set the default exception handler to a custom one
Thread.DefaultUncaughtExceptionHandler = new CustomExceptionHandler(
    Thread.DefaultUncaughtExceptionHandler);

我不知道這種方法有什么問題,它確實構建了但是我在運行時得到了一個InvalidCastException

錯誤圖片

我的CustomExceptionHandlerDefaultUncaughtExceptionHandler具有相同的Thread.IUncaughtExceptionHandler接口類型,但為什么我會收到此錯誤? 請賜教。 謝謝。

它再次襲來:D這是一個常見的錯誤。 如果實現Java接口,則必須繼承Java.Lang.Object

public class CustomExceptionHandler : Java.Lang.Object, Thread.IUncaughtExceptionHandler
{
    public void UncaughtException(Thread t, Throwable e)
    {
        // Submit exception details to a server
        ...

        // Display error message for local debugging purposes
        Debug.WriteLine(e);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM