3

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.

Community
  • 1
  • 1
arvicxyz
  • 381
  • 3
  • 13
  • 1
    Try a `JavaCast` here. https://developer.xamarin.com/api/member/Android.Runtime.Extensions.JavaCast%7BTResult%7D/p/Android.Runtime.IJavaObject/ – Jon Douglas Sep 23 '16 at 19:33
  • @JonDouglas I have used it. Thread.DefaultUncaughtExceptionHandler = Extensions.JavaCast( new CustomExceptionHandler(Thread.DefaultUncaughtExceptionHandler)); But still I get the same error. – arvicxyz Sep 24 '16 at 16:42

1 Answers1

18

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);
    }
}
Graham
  • 7,431
  • 18
  • 59
  • 84
Sven-Michael Stübe
  • 14,560
  • 4
  • 52
  • 103