gpt4 book ai didi

xamarin - Xamarin跨平台中的全局异常处理

转载 作者:行者123 更新时间:2023-12-02 11:42:51 26 4
gpt4 key购买 nike

您能否告诉我如何处理 Xamarin 跨平台项目中的全局异常(不导致应用程序崩溃)。

最佳答案

据我所知,没有“Xamarin.Forms”方法可以做到这一点。您需要 Hook Android 和 iOS,您可以做的就是创建一种以相同方式处理它们的方法。

不错的post彼得·诺曼(Peter Norman)对此进行了介绍。他描述说,要在 Android 中实现它,您可以在 MainActivity.cs 中执行此操作。

// In MainActivity
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);

AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;

Xamarin.Forms.Forms.Init(this, bundle);
DisplayCrashReport();

var app = new App();
LoadApplication(app);
}

‪#‎region‬ Error handling
private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);
LogUnhandledException(newExc);
}

private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
var newExc = new Exception("CurrentDomainOnUnhandledException", unhandledExceptionEventArgs.ExceptionObject as Exception);
LogUnhandledException(newExc);
}

internal static void LogUnhandledException(Exception exception)
{
try
{
const string errorFileName = "Fatal.log";
var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // iOS: Environment.SpecialFolder.Resources
var errorFilePath = Path.Combine(libraryPath, errorFileName);
var errorMessage = String.Format("Time: {0}\r\nError: Unhandled Exception\r\n{1}",
DateTime.Now, exception.ToString());
File.WriteAllText(errorFilePath, errorMessage);

// Log to Android Device Logging.
Android.Util.Log.Error("Crash Report", errorMessage);
}
catch
{
// just suppress any error logging exceptions
}
}

/// <summary>
// If there is an unhandled exception, the exception information is diplayed
// on screen the next time the app is started (only in debug configuration)
/// </summary>
[Conditional("DEBUG")]
private void DisplayCrashReport()
{
const string errorFilename = "Fatal.log";
var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var errorFilePath = Path.Combine(libraryPath, errorFilename);

if (!File.Exists(errorFilePath))
{
return;
}

var errorText = File.ReadAllText(errorFilePath);
new AlertDialog.Builder(this)
.SetPositiveButton("Clear", (sender, args) =>
{
File.Delete(errorFilePath);
})
.SetNegativeButton("Close", (sender, args) =>
{
// User pressed Close.
})
.SetMessage(errorText)
.SetTitle("Crash Report")
.Show();
}

‪#‎endregion‬

对于 iOS,您可以在 AppDelegate.cs 中添加这样的代码。

//iOS: Different than Android. Must be in FinishedLaunching, not in Main.
// In AppDelegate
public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary options)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
// Rest of your code...
}

/// <summary>
// If there is an unhandled exception, the exception information is diplayed
// on screen the next time the app is started (only in debug configuration)
/// </summary>
[Conditional("DEBUG")]
private static void DisplayCrashReport()
{
const string errorFilename = "Fatal.log";
var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Resources);
var errorFilePath = Path.Combine(libraryPath, errorFilename);

if (!File.Exists(errorFilePath))
{
return;
}

var errorText = File.ReadAllText(errorFilePath);
var alertView = new UIAlertView("Crash Report", errorText, null, "Close", "Clear") { UserInteractionEnabled = true };
alertView.Clicked += (sender, args) =>
{
if (args.ButtonIndex != 0)
{
File.Delete(errorFilePath);
}
};
alertView.Show();
}

它还包括在调试应用程序时显示日志的功能。当然,您可以实现自己的日志记录或处理方法。您可以查看的一件事是 HockeyApp 。默认情况下,这会处理未处理的异常,并将它们发送回给您等。

更新,因为在 Google 上仍然可以找到此内容:对于崩溃报告和分析,您现在需要开始查看 App Center 。这是 HockeyApp 和 Xamarin Insights(以及其他构建、分发和推送通知等)的发展,现在充当与应用程序相关的所有内容的任务仪表板,而不仅仅是 Xamarin。

对于 UWP 和 WinPhone 8.1,Application 对象中应该有一个 UnhandledException 处理程序。查看this answer了解更多信息。我引用:

For XAML-based apps, you can use UnhandledException; however, that only captures exceptions that come up through the XAML (UI) framework and you don't always get a lot of information about what the root cause is, even in InnerException.

Update for Windows 8.1: UnhandledException also will capture exceptions that are created by an async void method. In Windows 8, such exceptions would just crash the app. LunarFrog has a good discussion of this on their website.

基本上,您应该在 App.xaml.cs 中的 App() 的构造函数中添加一个事件处理程序:this.UnhandledException += (o, s) => {}

关于xamarin - Xamarin跨平台中的全局异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57200985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com