如何在Xamarin.Android中正确编写自定义UncaughtExceptionHandler

arv*_*xyz 2 c# android xamarin.android xamarin

我想要实现的只是捕获我的应用程序上的异常,以便我可以将它们发送到服务器.我想通了,我可以写我的自定义为此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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我使用这个类在我的Activity中设置DefaultUncaughtExceptionHandler:

// Set the default exception handler to a custom one
Thread.DefaultUncaughtExceptionHandler = new CustomExceptionHandler(
    Thread.DefaultUncaughtExceptionHandler);
Run Code Online (Sandbox Code Playgroud)

我不知道这种方法有什么问题,它确实构建了但是我在运行时得到了一个InvalidCastException.

错误图片

我的CustomExceptionHandlerDefaultUncaughtExceptionHandler具有相同的Thread.IUncaughtExceptionHandler接口类型,但为什么我会收到此错误?请赐教.谢谢.

Sve*_*übe 11

它再次袭来:D这是一个常见的错误.Java.Lang.Object如果实现Java接口,则必须继承.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)