Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c# - How to properly write a custom UncaughtExceptionHandler in Xamarin.Android

All I want to achieve is to catch exceptions on my app so that I can send them to a server. I figured out that I can do this by writing my custom UncaughtExceptionHandler base on native Android code in Java answered here in StackOverflow.

This is my CustomExceptionHandler class:

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

Then I used this class to set the DefaultUncaughtExceptionHandler in my Activity:

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

I don't know what is wrong with this approach, it did build but I got an InvalidCastException on runtime.

Error Image

I have the same Thread.IUncaughtExceptionHandler interface types for my CustomExceptionHandler and the DefaultUncaughtExceptionHandler, but why am I getting this error? Please enlighten me. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

And it strikes again :D This is a common mistake. You have to inherit Java.Lang.Object if you implement Java interfaces.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...