【问题标题】:How to properly write a custom UncaughtExceptionHandler in Xamarin.Android如何在 Xamarin.Android 中正确编写自定义 UncaughtExceptionHandler
【发布时间】:2017-02-01 18:06:51
【问题描述】:

我想要实现的只是在我的应用程序上捕获异常,以便我可以将它们发送到服务器。我发现我可以通过基于 Java 中的原生 Android 代码编写自定义 UncaughtExceptionHandler 来做到这一点,在 StackOverflow 中回答了 here

这是我的 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 接口类型,但为什么会出现此错误?请赐教。谢谢。

【问题讨论】:

  • 在这里试试JavaCast<T>developer.xamarin.com/api/member/…
  • @JonDouglas 我用过。 Thread.DefaultUncaughtExceptionHandler = Extensions.JavaCast(new CustomExceptionHandler(Thread.DefaultUncaughtExceptionHandler));但我仍然得到同样的错误。

标签: c# android xamarin xamarin.android


【解决方案1】:

它又来了 :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);
    }
}

【讨论】:

  • 绝对是问题的答案。谢谢你。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-21
相关资源
最近更新 更多