如何在 Xamarin.Android 中正确编写自定义 UncaughtExceptionHandler [英] How to properly write a custom UncaughtExceptionHandler in Xamarin.Android
问题描述
我想要实现的只是在我的应用程序上捕获异常,以便我可以将它们发送到服务器.我发现我可以通过编写基于 Java 原生 Android 代码的自定义 UncaughtExceptionHandler 来做到这一点回答
我的 CustomExceptionHandler 和 DefaultUncaughtExceptionHandler 具有相同的 Thread.IUncaughtExceptionHandler 接口类型,但为什么会出现此错误?请赐教.谢谢.
它又来了 :D 这是一个常见的错误.如果您实现 Java 接口,则必须继承 Java.Lang.Object
.
public class CustomExceptionHandler : Java.Lang.Object, Thread.IUncaughtExceptionHandler{public void UncaughtException(Thread t, Throwable e){//向服务器提交异常详细信息...//为本地调试目的显示错误信息Debug.WriteLine(e);}}
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.
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.
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);
}
}
这篇关于如何在 Xamarin.Android 中正确编写自定义 UncaughtExceptionHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!